- Home /
SerializedProperty to Texture2D
I'm currently making a custom propertydrawer, and I want to draw a preview of a sprite field. So the question is pretty simple let's say I have this SerializedProperty:
property.FindPropertyRelative("Sprite")
How do I convert this into a Texture2D? SerializedProperty doesn't have any property method that returns a Texture or Texture2D. I tried using the "objectReferenceValue" and then cast to Texture, but with no success.
If someone was able to make this, please enlighten me. Thank you.
Answer by Ted Ocean · Feb 28, 2015 at 02:44 PM
I am using the same cast which works for a property attribute drawer, it should also work for a custom class property drawer. Here is what I use:
var texture = (Texture2D)property.objectReferenceValue;
Note I'm also checking for null before this, it may be blank which could be why your cast is failing. See the below awesome collection of property drawers, this is definitely the way to write them.
There is a display Texture2D sprite drawer in there as well: https://github.com/anchan828/property-drawer-collection/tree/master/PreviewTexture
Answer by Ziplock9000 · Jul 18, 2019 at 10:56 PM
This shows the drag n drop field and shows the icon when there's one selected and uses the latest custom inspector code that works in U2019:
SerializedProperty sp = serializedObject.FindProperty("Icon");
EditorGUILayout.PropertyField(sp);
Texture2D texture = AssetPreview.GetAssetPreview(sp.objectReferenceValue);
if (texture != null) GUILayout.Label(texture);
Your answer
Follow this Question
Related Questions
Make a PropertyField() for a Texture2D SerializedProperty looking like an ObjectField() 2 Answers
Call a function from CustomPropertyDrawer of Arbitrary class 1 Answer
Display Custom Inspectors for each class in a List<> 1 Answer
Applying a PropertyDrawer to elements of a List<> 1 Answer
Texture2D on Property Drawers. 0 Answers