- Home /
Activating a prefab in the scene by find it over a tag?
Hello everyone, i want to activating a prefab. To do this i want to use a tag, to find the GameObject and then use SetActive(true) to set set it active. I tried this code but it doesnt work.
private int ActiveCannon;
public GameObject Cannon1;
public GameObject Cannon2;
public GameObject Cannon3;
public GameObject Cannon4;
public GameObject Cannon5;
public GameObject Cannon6;
void Start () {
ActiveCannon = PlayerPrefs.GetInt("ActiveCannon");
if (ActiveCannon == 1)
{
Cannon1 = GameObject.FindWithTag("Cannon1");
Cannon1.SetActive(true);
}
if (ActiveCannon == 2)
{
Cannon2 = GameObject.FindWithTag("Cannon2");
Cannon2.SetActive(true);
}
if (ActiveCannon == 3)
{
Cannon3 = GameObject.FindWithTag("Cannon3");
Cannon3.SetActive(true);
}
if (ActiveCannon == 4)
{
Cannon4 = GameObject.FindWithTag("Cannon4");
Cannon4.SetActive(true);
}
if (ActiveCannon == 5)
{
Cannon5 = GameObject.FindWithTag("Cannon5");
Cannon5.SetActive(true);
}
if (ActiveCannon == 6)
{
Cannon6 = GameObject.FindWithTag("Cannon6");
Cannon6.SetActive(true);
} }
Sorry for my bad english.
So what does not work? Because the actual code does this:
You find a reference to tag "Cannon6" and you assign to a Cannon6 variable, then you make that gameobject active (you enable it). What does sets the int? (activecannon)
Have you tried debugging (setting breakpoints in visual studio) ?
Is the prefab arleady in the scene? If you are referencing then it must be, otherwise it has to be instantiated.
Answer by WarmedxMints · Feb 26, 2019 at 02:29 PM
I believe FindWithTag only returns active gameobjects so you would need to store a reference to your cannons somewhere and activate from that.
I would suggest you make a List in a manager somewhere and have the cannons add themselves to it on start. You can then just active an index in that List.