Inspector Assigned Variables Not In Both Scenes

So I have more of a general Unity programming question…

If I have a script that runs in two different scenes, which has a GameObject variable (assigned via the inspector) which only exists in one of those scenes, how do I get past/avoid UnassignedReferenceException errors due to not being able to assign that GameObject in the scene where it doesn’t exist?

I’m stumped and it’s causing me some headache. Any advice is appreciated!

Some options:

  • Assign the variable in code during Awake() or Start(). Find it by name, by tag, by component type, etc. and then validate that you got it.
  • If it makes sense to do so, make the assigned object a child of the object looking for it. Then, make the parent a prefab. The assigned link in the prefab will be maintained when the prefab is instantiated in other scenes, by editor placement or by code.
  • Have a singleton and/or static class use either of the above to keep track of the object, then reference it via that class.