Reference Scene component from Prefab component

I have a Class component on a Prefab which I instantiate.
In the scene there exists a Gameobject that this Prefab component needs a reference to.

In other words the Prefab component needs to reference an already existing component in the scene.

How best to accomplish this?

A few ways you could do it off the top of my head:

  • Give your object in the scene a tag, then find that object in your prefab component in Start() using GameObject.FindWithTag. and get the particular component with GetComponent<TheSceneComponentType>()
  • Make your object in the scene use one of the well-known singleton patterns. For example: c# - In Unity, how do I correctly implement the singleton pattern? - Game Development Stack Exchange
  • Find the object in the scene by traversing the scene hierarchy. For example if you know you are instantiating the prefab in the scene as a child of the scene component, you can find the scene component with GetComponentInParent<TheSceneComponentType>()
1 Like

You will need to have an object in the scene that has the reference you need, and then find that object via code from your prefab. A common way to approach this is the “singleton pattern”, where you have a scene manager in the scene (with all your references), and can access it through a static reference. (This is sort of the same way that “Camera.main” works.)

public class SceneManager : MonoBehaviour {
public GameObject thingYouWant; //assign this in the inspector

public static SceneManager Instance;

void Awake() {
Instance = this;
}
}

// in any other object, anywhere
transform.LookAt(SceneManager.Instance.thingYouWant.transform.position);
1 Like