References to scene objects in prefabs - Inspector vs. Find

Hello all,

I feel like beeing in an endless loop…

I have a LevelUIManager holding a reference to a text UI object “txt_currentSpeed”.
179463-1.jpg

public class LevelUIManager : MonoBehaviour {
    public Text txt_Distance;

My first approach was to use the inspector to bind the text object to the public field of my LevelUIManager class.
179464-2.jpg

My LevelUIManager is a prefab in order to use it in every level and with this approach I was facing the problem that the references were not working when reusing this prefab in different scenes and after some research I found out that it is not possible to reference scene objects from a prefab. Okay, that’s a pity, but the solution I found everywhere was “use GameObjects.Find()” to get the reference.

Okay, hence, my second approach looks like this:

private GameObject completeLevelUI;
private Text txt_Distance;

private void Start()
{
    txt_Distance = GameObject.Find("txt_Distance").GetComponent<Text>();
    completeLevelUI = GameObject.Find("LevelComplete");

While getting the txt_Distance reference works fine, getting the LevelComplete reference does not work since it is a panel which I disabled in order to active it when I need it.

Doing some research again brought up lots results which say: “Find() is always the worst method to use to get a reference, use the inspector instead”

GREAT, now I am at the beginning again…

That is the point where I want to ask you to explain me, which is a meaningful way to deal with my issues.

  1. When can / should I use the inspector method
  2. When can / should I use find()
  3. What is a good way to get a reference to a disabled object

Thanks in advance!

You are right that an object from scene cannot be referenced by a Prefab. In your case, the solution is: create LevelUIManager in the scene and its references would be its children. Then you can drag LevelUIManager to your asset as prefab. Now you can use this prefab in several scene without reference problem.

When can / should I use find()
Avoid Find() if you can. Behind the scene, Unity iterates through all objects in the scene to find the object(s). If your scene is large, using Find() costs a lot of overhead to your CPU. In other hand, using Find() creates “Hidden logic”, it means some objects are depend on some objects but you cannot see those dependencies in Unity Editor.
I think, the best use case for Find() is when you want to quick test your logic while coding.

What is a good way to get a reference to a disabled object
Use Inspector.

When can / should I use the inspector method
Use Inspector if you can. Inspector is a very powerful tool, it can be a Dependency Injector, a Debugger or even a Design Tool for Game Designer. It is the connect point of all roles in a team (Programmer, Game Designer or Artist would get better view of project structure if the game logic is present well in the Inspector)