With Debug.Logs.
What I meant by “check something at runtime” is that you log values into your console. For instance, just because your program executes GameObject objectToDestroy = GameObject.Find(“Groundj”);
does not mean that objectToDestroy
references an object after this line. That line of code might be perfectly fine but it might be that the Find method cannot find any game object named “Groundj” at that moment when it gets executed. And when does the line get executed? After you clicked the Play button. At runtime.
The same applies to the trigger method. Nice method but we cannot know if it gets executed at runtime. For this reason, logging a message into our console could help us learn what’s going on at runtime.
Here is an example:
void OnTriggerEnter2D(Collider2D other)
{
Debug.Log("OnTriggerEnter2D was called.");
// the rest of the code
}
If the message does not appear in your console, you know that OnTriggerEnter2D has not been called. In that case, you don’t have to waste your time with the if-statement because the if-condition does not get checked if the method does not get called.
Did this make sense?
If so, try to figure out what works and what does not work. A few “simple” Debug.Logs with meaningful messages should be sufficient.
Regarding CompareTag: if (other.CompareTag("Ground")) { }
. You want use an if-statement, thus you need the if
. Inside the parentheses, a boolean expression is required. The CompareTag method returns either true or false.
Alternatively, you could write:
bool correctTag = other.CompareTag("Ground");
if (correctTag)
{
// your code
}
Bear in mind, though, that bixarrio’s suggestion was a suggestion for improving the performance of your code. CompareTag will not solve your actual problem. For this reason, it’s better to focus on your problem with the OnTrigger* method for now. You can change your code (if you want) once the problem is fixed.