Created
April 8, 2020 00:41
-
-
Save daniel-ilett/99992dfcb565324c76a655e16115aedf to your computer and use it in GitHub Desktop.
A Unity editor script which lets you save a Gradient as a texture file (place the script inside a folder named Editor).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
using UnityEditor; | |
using System.IO; | |
public class GradientWindow : EditorWindow | |
{ | |
private Gradient gradient = new Gradient(); | |
private int resolution = 256; | |
private string filename = "New Texture"; | |
private FileFormat format = FileFormat.PNG; | |
[MenuItem("Window/Gradient2PNG", priority = 10000)] | |
public static void ShowWindow() | |
{ | |
GetWindow<GradientWindow>(false, "Gradient2PNG", true); | |
} | |
private void OnGUI() | |
{ | |
EditorGUILayout.LabelField("Gradient to File Converter"); | |
gradient = EditorGUILayout.GradientField("Gradient", gradient); | |
resolution = EditorGUILayout.IntField("Resolution", resolution); | |
filename = EditorGUILayout.TextField("Filename", filename); | |
format = (FileFormat)EditorGUILayout.EnumPopup("Format", format); | |
GUILayout.FlexibleSpace(); | |
if(GUILayout.Button("Convert to asset", GUILayout.Height(50))) | |
{ | |
ConvertGradient(); | |
} | |
} | |
private void ConvertGradient() | |
{ | |
Texture2D tex = new Texture2D(resolution, 1); | |
Color[] texColors = new Color[resolution]; | |
for(int x = 0; x < resolution; ++x) | |
{ | |
texColors[x] = gradient.Evaluate((float)x / resolution); | |
} | |
tex.SetPixels(texColors); | |
byte[] bytes = null; | |
string filenameWithExtension = null; | |
switch(format) | |
{ | |
case FileFormat.JPG: | |
bytes = tex.EncodeToJPG(); | |
filenameWithExtension = "/" + filename + ".jpg"; | |
break; | |
case FileFormat.PNG: | |
bytes = tex.EncodeToPNG(); | |
filenameWithExtension = "/" + filename + ".png"; | |
break; | |
case FileFormat.TGA: | |
bytes = tex.EncodeToTGA(); | |
filenameWithExtension = "/" + filename + ".tga"; | |
break; | |
} | |
try | |
{ | |
string path = Application.dataPath + filenameWithExtension; | |
var dir = Path.GetDirectoryName(path); | |
if (!Directory.Exists(dir)) | |
{ | |
Directory.CreateDirectory(dir); | |
} | |
File.WriteAllBytes(path, bytes); | |
AssetDatabase.Refresh(); | |
} | |
catch(IOException e) | |
{ | |
Debug.LogError(e); | |
} | |
} | |
} | |
public enum FileFormat | |
{ | |
JPG, | |
PNG, | |
TGA | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment