Default Asset References for a Script

I noticed that if you select a Monobehavior script in the project tab, you can see all the Monobehavior’s public variables in the inspector. It looks like you can insert default links here which would be insanely useful. However, when I assign an asset here, it does not show up when I actually add the component to a GameObject - it goes back to “None”.

The reason I’d like to do this is so I can easily access a shader asset that I want to use in the script. If I don’t do it this way, I need to find some prefab to add a reference to the shader or create a prefab for this script, but both seem wasteful or backwards.

Is this supposed to work, or am I doing something wrong? It looks like this should work like Unreal’s “defaultproperties” section (which again, would be awesome).

When creating/adding Components via script, the Inspector default references are ignored, since it is an Editor-only feature.

But there are other workarounds you can use in this case. For example:

  • create a prefab where the object is already constructed and assigned as desired (if that’s possible)
  • hardcode and create the required references in the script (e.g., new Material(Shader.Find("MyShaderName")) etc.) and assign them to the Component you just created
  • create all necessary default references as public variables in the script that does the AddComponent(), and then assign these public variables via scripting to the Component after you created it. Then you can assign these references in the Inspector (although still not via the “default references” option).

The last suggestions is probably the most convenient one, but it depends on the situation.