Disabling components on objects with tags
Hello, this is my first post, so forgive me if i make some mistakes. I'm trying to disable the same 2 script components on 2 different tags. It works fine on one of the tags, but the other one doesn't work, it gives me the error "Object reference not set to an instance of an object". Here's the code:
void PowerUp()
{
WinSound();
foreach (GameObject go in GameObject.FindGameObjectsWithTag("PickUp"))
{
go.GetComponent<Patrol>().enabled = false;
go.GetComponent<Rotate>().enabled = false;
}
foreach (GameObject go in GameObject.FindGameObjectsWithTag("Enemy"))
{
go.GetComponent<Patrol>().enabled = false;
go.GetComponent<Rotate>().enabled = false;
}
}
It works just fine on the PickUp tag, but on the Enemy tag it gives me that error. Hope you can help, please tell if you need more info. Thanks a lot in advance!
Answer by TBruce · May 12, 2016 at 08:26 PM
Here is your function with debug statements so that you can see exactly where the error lies
void PowerUp()
{
WinSound();
foreach (GameObject go in GameObject.FindGameObjectsWithTag("PickUp"))
{
if (go.GetComponent<Patrol>() != null)
{
go.GetComponent<Patrol>().enabled = false;
}
else
{
Debug.LogWarning(go + " does not contain a component of type Patrol. Please add one.");
}
if (go.GetComponent<Rotate>() != null)
{
go.GetComponent<Rotate>().enabled = false;
}
else
{
Debug.LogWarning(go + " does not contain a component of type Rotate. Please add one.");
}
}
foreach (GameObject go in GameObject.FindGameObjectsWithTag("Enemy"))
{
if (go.GetComponent<Patrol>() != null)
{
go.GetComponent<Patrol>().enabled = false;
}
else
{
Debug.LogWarning(go + " does not contain a component of type Patrol. Please add one.");
}
if (go.GetComponent<Rotate>() != null)
{
go.GetComponent<Rotate>().enabled = false;
}
else
{
Debug.LogWarning(go + " does not contain a component of type Rotate. Please add one.");
}
}
}
@$$anonymous$$avina Thanks so much for your answer. So i'm kinda new to C# and don't understand all these codes properly. Not sure what the Debug.LogWarning was suppose to do? Anyway this code fixes the issue apparently, it now works just fine. I would like to understand why though, and also under what the Debug.LogWarning was suppose to do. Thanks again.
NP. Glad I could help. Here are the docs on Debug.
Basically I just took your code and verify each object was valid before you tried to use it. If it was not I spit out a message to the console to let you know what the problem was.