Prefab to activate Scene Object

Hi Guys,

so I know I need to reference scene objects to prefabs that are spawned in (it’s and item system). When “picking up” something, a buitton is activated. Pressing this new button (or item) should do something. Well, it doesn’t. I have prepared a “simple” case:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Hate : MonoBehaviour
{

    GameObject door;

    public void Start()
    {
        door = GameObject.FindGameObjectWithTag("Door");
    }

   public void OpenDoor()
    {
        Debug.Log("Activated");
        if(door != null)
        {
            door.SetActive(true);
        }
    }
}

I thought with finding the object with the “Door” tag I could activated it (the code does work when used with objects that are basic scene objects, just not with the prefab that is added later to the scene).

Can someone help me how to reference to the object as I clearly am doing something wrong?

Thanks!

If the door is added later, getting it’s reference in Start() is too early. Even if it’s added in another Start(), it will depend on script execution order. (Unity - Manual: Order of execution for event functions)
To avoid this you can check if door have a reference before using it.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Hate : MonoBehaviour
{
    GameObject door;

    public void OpenDoor()
    {
        Debug.Log("Activated");
        if (door != null)
        {
            door.SetActive(true);
        }
        else // Get door ref if there's none
        {
            door = GameObject.FindGameObjectWithTag("Door");
        }
    }
}

If there’s going to be more than one door in your scene, you’ll need another way to find your door as FindGameObjectWithTag() will return the first gameObject it finds.

Hey mate, sorry I did not include this - the door is already in the scene, just not active. It’s a button that is added with the “hate” (just because I already lost my mind lol) script on it!

You can’t find inactive gameobjects. There are some alternatives here - How to find an inactive game object? - Questions & Answers - Unity Discussions

The real solution is to not do it this way.

You could have a level script that references all the doors, then just find the level gameobject instead.

Oh. That explains a lot.

But I could have the object active but a certain script on it not and activate that script?

let’s just say the “Door” is a 2D Collider set to Trigger. There is a Script on it that sends the player to another position in the level. On the beginning of the scene, the “Door” is active, but the “Send” script component on it is not. I know spawn my prefab to the scene - this can now find the door and activate the “send”?

Let’s pretend there is no other, better and more efficient way, I am sure tehre are hundreds, but I try to understand and get it done now before trying to make it better :slight_smile: