Home > Software engineering >  How to reference a gameObject inside a prefab? Using GameObject.Find does not work
How to reference a gameObject inside a prefab? Using GameObject.Find does not work

Time:04-25

I am trying to use GameObject.Find within a prefab to reference an object that exists in the scene. The name of the object is exactly the same as the actual object.

    LoseLives loseLives;
    GameObject loseLivesing;

    private void Awake()
    {
        loseLivesing = GameObject.Find("MasterManager");
    }
    private void Start()
    {
        loseLives = loseLivesing.GetComponent<LoseLives>();
        target = Waypoints.waypoints[0];
      
    }

    loseLives.LoseLife();

Inspector

It comes with the problem of needing to constantly drag your constant object into the inspector whenever you need it.

For a Prefab, it works if the target object is part of the Prefab, or the Prefab is generated in the same scene as the targeted object.


Second Method

Using singletons.

LoseLives.cs

public class LoseLives : MonoBehaviour {

    public static LoseLives Instance {
        get => Instance;
    }

    private static LoseLives instance;

    private void Start() {
        instance = this;
    }

    public void LoseLife() {
        // ...
    }
}

YourScript.cs

public class YourScript : MonoBehaviour {
    // ..
    private void Start() {
        LoseLives.Instance.LoseLife();
    }
    // ..
}

This works if you have a global, singular instance of LoseLives object.

CodePudding user response:

Even though it might not be the best approach, I found a workaround for my issue.

I am using a static variable that resides in the other script (CurrencyManager), calling it from the LoseLives script.

Instead of:

loseLives.LoseLife();

I do:

CurrencyManager.playerHealth -= 1;

Where CurrencyMananger is the other script and playerHealth is a static variable that is in the CurrencyManager script. This works because a static variable does not require the objects to be referenced in the inspector.

From now on, when I have a problem where I want to reference a gameObject within a script that is on a prefab, I will consider using static variables in my solution.

  • Related