I have a class with an Texture2D attribute. In theory you would take a texture somewhere in your Assets folder and drag it onto the inspector field of that texture attribute.
Is it possible to do that by script? I would assume EditorGUIUtility.FindTexture is exactly what I need, but for some reason it doesn’t find my texture. My texture filename is “Assets/layer.png” and I tried these parameters for FindTexture:
You could use EditorGUILayout.ObjectField, which serves the purpose of dragging&dropping + referencing assets.
It has an objType parameter which has to be typeof(Texture2D) in your case (this is actually the filter, so it won’t let you drop any other asset type into your field).
Thanks, but I have already an ObjectField. What I was trying to do is to avoid the drag&dropping by doing that by script.
Anyway, I finally got it:
public class Layer : MonoBehaviour {
public Texture2D texture = null;
// ... lots of stuff here ...
}
[CustomEditor(typeof(Layer))]
public class LayerEditor : Editor {
private Layer layer;
void OnEnable () {
layer = target as Layer;
}
public override void OnInspectorGUI() {
serializedObject.Update();
EditorGUIUtility.LookLikeInspector();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("Layer Texture");
layer.texture = EditorGUILayout.ObjectField(layer.texture, typeof(Texture2D), false) as Texture2D;
EditorGUILayout.EndHorizontal();
GUILayout.Space(5.0f);
// ... lots of stuff here ...
if (GUILayout.Button("Create"))
CreateTexture();
// ... lots of stuff here ...
}
private void CreateTexture() {
Texture2D texture = new Texture2D(size.x, size.y, format, false);
byte[] data = texture.EncodeToPNG();
// ... save binary data to file ...
// automatically link created texture to our Layer object
texture = (Texture2D)AssetDatabase.LoadAssetAtPath(filename, typeof(Texture2D));
if (texture == null)
Debug.LogError("Could not read " + filename);
else
layer.texture = texture;
}
}