- Home /
NullReferenceException when trying to get Collider2D's parent gameObject
As part of getting to know Unity I'm making a simple fighting game with two characters and two moves (punch and kick). The game works by activating a trigger hitbox in front of the player when punching or kicking.
The following script is supposed to check the tag of the hitbox (either "hitboxPunch" or "hitboxKick") to calculate the damage and then check whether the hitbox belongs to you or the opponent so that you won't get damage from your own.
void OnTriggerEnter2D(Collider2D other)
{
string trigTag;
string trigParent;
trigTag = other.gameObject.tag;
trigParent = other.gameObject.transform.parent.gameObject.tag; // line 151
Debug.Log("trigTag is " + trigTag + ", trigParent is " + trigParent); // line 153
// Damage calculations etc go here
}
After punching the opponent and triggering the function above the game freezes and I get following lines on my console window:
NullReferenceException: Object reference not set to an instance of an object PlayerAttack.OnTriggerEnter2D (UnityEngine.Collider2D other) (at Assets/scripts/PlayerAttack.cs:151)
trigTag is punchHitbox, trigParent is Player1 UnityEngine.Debug:Log(Object) PlayerAttack:OnTriggerEnter2D(Collider2D) (at Assets/scripts/PlayerAttack.cs:153)
If I comment out line 151 the game works fine.
Thanks in advance!
Answer by Sienj · Jun 27, 2014 at 12:21 PM
Problem solved!
As the script was applied to both players, the line "other.gameObject.transform.parent.gameObject.tag" was trying to access not only the parent of the hitbox, but also parent of the other player, which was already a top level gameObject. This is why I got the error message.
Your answer
Follow this Question
Related Questions
NullReference when accessing GameObject in array (C#) 1 Answer
Translate.transform problems (collision/Rigibody) 0 Answers
How can I check if an instantiated object collides with another instantiated object? 1 Answer
How to null-reference check a Collider2D that's been destroyed 1 Answer
Why are my GameObjects null when I add them to a List? 3 Answers