EditorGUILayout - Use of unassigned local variable

I have a custom class UISprite (from NGUI), a variable of type UISprite in my equipmentSlot class, and I am trying to expose that variable in my custom inspector, so I can set it by dragging and dropping in edit mode. To that end, in OnInspectorGUI I’ve written

UISprite equipmentSprite  = EditorGUILayout.ObjectField (equipmentSprite,typeof(UISprite),true);

However, this produces an error, to wit “Use of unassigned local variable equipmentSprite”. Is my syntax completely off, or am I just using GUILayout incorrectly?

In you original script, try to set the corresponding variable to null in the declaration:

UISprite equipmentSprite = null;

I would think that the editor mode doe snot initialized the references like runtime does, so your reference is garbage until you would drag something into it. So when the editor script tries to read it it finds the garbage and throws the exception you mentioned.

Hey There,

You just have to break down your code to find out why it’s not working.

UISprite equipmentSprite
  1. You are saying I am making a new UISprite which by default is null [you made the container but not the object that is inside the container]

    EditorGUILayout.ObjectField (equipmentSprite,typeof(UISprite),true);

  2. If you notice you are using equipmentSprite which as you look from the first step is empty or better put null.

The poor function has no idea what equipmentSprite is since you never set it (ObjectFeild can’t do anything with a null object). This is why you get the error.

You should do this.

[CustomEditor(typeof(UISprite))]
public class MyClass : Editor
{

   private void OnInspectorGUI()
   {
      UISprite sprite = target as UISprite;

      UISprite = EditorGUILayout.ObjectFeild( sprite , typeof(UISprite), true);
   }
}

You will notice that I am using “target”. The way you have it set up right now (if it did work)it would save the UISprite to the inspector class. This information would get lost as soon as you click off the object since this class is destroyed. You have to save everything to your target class (this is the class that the inspector is drawing for)

Regards,