Set Hierarchy Object Active from Instantiated Object
I have a Canvas that is Inactive in the Hierarchy. When an instantiated object (Object A) collides with a specific object in the hierarchy (Object B) there is a script on Object B that will set the Canvas to active and set text to something. That works fine.
But I want to do the same thing with two objects that are instantiated (Objects A and C collide). I can't get Object A to reference the Canvas in the Hierarchy. I turned the Canvas into a prefab and linked the two objects that way, and it won't give me any errors, but when I call SetActive(true) from the instantiated Object A nothing happens.
I've also tried tagging the Canvas and FindGameObjectWithTag during Start() but that throws an error.
// LevelExit.cs
// This Works
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Hero")
{
notice.gameObject.SetActive(true);
noticeText.text = "Press 'A' to go to next Level!";
}
}
// HeroScript.cs
//This Doesn't
public Canvas notice; // Prefab of canvas (already in hierarchy)
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "enemy")
{
notice.gameObject.SetActive(true);
notice.GetComponentInChildren<Text>().text = "You hit an enemy";
}
}
You seem to be mixing up instances and prefabs. You have apparently created a prefab of your canvas and then linked that newly created prefab to the (prefabs of the) instantiated objects. But of course the prefab is not the same as the canvas in the hierarchy. It is just the prefab for the specific object in your scene.
"I've also tried tagging the Canvas and FindGameObjectWithTag during Start() but that throws an error." - Well, what error? Did you read it? If so, did you understand it? If not, please provide the error message, maybe then we can help.
That makes sense. Error is just the null reference error. The instantiated script isn't finding the tagged inactive Canvas. I assume it's because it's not active. I guess one work around is to put the script on the Canvas and make it active. Then make each individual element in the Canvas active and inactive as needed.
Your answer
Follow this Question
Related Questions
Problem with shooting multiple bullet at the same time with an Object Pooler 1 Answer
Turret not spawning fireball via instantiation in Unity 2d? 0 Answers
Instantiating multiple interactive prefabs 0 Answers
Need to add a reference to script once added with code? 0 Answers
.setActive(true) not functioning. 1 Answer