How can i make Prefabs change variables that are defined in another Script?

After alot of trying i found out that prefabs dont take Scripts or Gameobjects that are normally draged into the field of the Variable you define.

Now my question is: How can i make it so that a Prefab changes a Variable of another script?

    public GameManager GameManager;

    void Awake() 
    {
        StartCoroutine("TimeToDeath");
    }

    IEnumerator TimeToDeath()
    {
        
        yield return new WaitForSeconds(3f);
        Destroy(gameObject);
        yield return new WaitForSeconds(1.5f);
        GameManager.currentSprites--;

        //This does NOT work since the Prefabs dont take the GameManager object in
    }

currentSprites is NOT a variable of the shown script. It is a variable of a script by an empty gameobject that manages alot of variables.

Now, how can i decrese this variable everytime the TimeToDeath() coroutiene is called?

Thanks alot in advance!

More accurately, any object in your project assets cannot reference anything inside of a scene.

Though objects in scenes can reference other objects in the same scene, or in your project assets.

Usually something with the vague name of ‘GameManager’ is made to express a singleton pattern to make it globally accessible. Though patterns such as hooking up references during runtime is often a solution as well.

2 Likes

They actually can! -as long as the GameObject or script that you drag in to the field is also part of the same prefab. If you have multiple objects that reference each other, then you can make an empty parent object and save all of these objects as one single prefab.

Otherwise, you can wire-up instances in a scene, like Spiney199 mentioned.

The other option is to write scripts to find these dependencies dynamically.

1 Like