Pressing play Causes Re-instancing of material (Editor)

Ok. So I have a font asset and have created several text objects with the font asset in a scene. I then needed to change the colour of each text object to different, unique colours via the editor, So I created a script to do so and put it in “editor” folder to add the necessary Inspector objects (with @ExecuteInEditMode in the primary attached script). I did this because the colour of the font can only ever be one colour at a time-and it’s greyed out in the inspector, and I needed to change the colour for each text object.

How do I prevent the instanced material (with it’s new, picked colour) from being constantly replicated/instantiated each time it hits an OnInspectorGUI() event an GuiText is selected and PLAY is started? The font material is shown in the console as, “font material (Instance) (Instance) (Instance) (Instance) (Instance)” etc.

I only need the one original instance, so that the colour can be changed and preserved per text object. Not continued instances of instances! Apparently reading the material from the game object instantiates it every time or every time the thing is played… (sharedMaterial is obviously pointless because it’s a read-only shared material across all objects using that particular font asset). Do I destroy the material? How? When I restart Unity it seems to preserve the instances…

Do I for example, need to set mat to 0/null/Destroy() it when the play is stopped (if so, what is the event called)? The colour of the text objects must persist after save scene events, though.

–Ok, should I be using GUITexts? Is UnityGUI- GUISkins labels look the same? (Apparently you can’t easily change sizes with labels…)

—edit:

If it helps, this is the Inspector script part for the colour picker:

    target.guiText.material.color = EditorGUILayout.ColorField( "font colour:",

target.guiText.material.color );

I’m looking for ANY kind of Answer, even:

  • Use XYZ instead, it’s better.
  • It’s broke, try…

Anyone know anything at all about what the best course of action to take or what’s going on, please post below.

IIRC, making an assignment with ‘.material’ will indeed make a new instance, which means that your script will instantiate a new material every time OnInspectorGUI is called.

Is there a reason you need to do this programmatically? You’re going to have to use different materials for each different colored object anyway, so I’m not sure why you want to set this up via script.

As to the current problem, what you’ll probably want to do is grab a reference to the material as soon as the object is selected, and just make changes to that.

Post back if you need any more help.