Search Unity

  1. Unity 2020.1 has been released.
    Dismiss Notice
  2. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

Can I replace a sprite in an editor script?

Discussion in 'Immediate Mode GUI (IMGUI)' started by highlyinteractive, Jan 23, 2018.

  1. highlyinteractive

    highlyinteractive

    Joined:
    Sep 6, 2012
    Posts:
    94
    I'm trying to create an editor script that lets me swap the sprite in an image. My end goal is to have a UI prefab that I can quickly change the properties of (background image, text colour, icon, language etc) with a single enum dropdown.

    Currently I'm just trying to swap out the sprite. Is this possible?

    Here's my attempt so far:
    Code (CSharp):
    1. [CustomEditor(typeof(TextBox))]
    2. public class TextBoxEditor : Editor
    3. {
    4.     SerializedProperty m_Colour;
    5.  
    6.     public void OnEnable ()
    7.     {
    8.         m_Colour = serializedObject.FindProperty("Colour");
    9.     }
    10.  
    11.     public override void OnInspectorGUI ()
    12.     {
    13.         TextBox textBox = (TextBox)target;
    14.  
    15.         EditorGUILayout.PropertyField(m_Colour, new GUIContent("Box Colour"));
    16.         serializedObject.ApplyModifiedProperties();
    17.  
    18.         if (GUI.changed)
    19.         {
    20.             string guid = AssetDatabase.FindAssets("box_red")[0]; //hard coded sprite name for now
    21.             string guri = AssetDatabase.GUIDToAssetPath(guid);
    22.             Sprite spr = (Sprite)AssetDatabase.LoadAssetAtPath(guri, typeof(Sprite));
    23.  
    24.             textBox.SetSprite(spr); //sets sprite in main class - Image.sprite = spr;
    25.  
    26.             SceneView.RepaintAll();
    27.         }
    28.     }
    29. }
    I think I'm misunderstanding something because the Sprite is ending up null.

    Help or advice appreciated
     
  2. TonyLi

    TonyLi

    Joined:
    Apr 10, 2012
    Posts:
    10,568
    Are you checking that AssetDatabase.FindAssets and AssetDatabase.LoadAssetAtPath aren't returning null?

    Also, call serializedObject.Update() before EditorGUILayout.PropertyField. Otherwise serializedObject isn't guaranteed to be an accurate serialized representation of your object.
     
  3. highlyinteractive

    highlyinteractive

    Joined:
    Sep 6, 2012
    Posts:
    94
    I am - they're returning the correct values
     
  4. TonyLi

    TonyLi

    Joined:
    Apr 10, 2012
    Posts:
    10,568
    Then you may need to set it dirty. Make sure to read the important notes in that link, too.
     
unityunity