Referencing a script of a parent of a instantiated instance from another instantiated instance
I'm making a parrying system in a 2d game on unity. The idea is that when the enemy attacks the player can parry and that stuns the enemy (and vice versa). At this point when the player parries it instantiates a hitbox parrying instance that can collide with with the enemy's instantiated hitbox attacking instance. For this i have the function below:
void OnCollisionEnter2D(Collision2D target){
if(target.gameObject.tag == targetTag){
if(actionType == ActionType.Attacking && target.gameObject.GetComponent<SwordHitbox>().actionType == ActionType.Attacking){
Debug.Log("Attack hits attack");
}
if(actionType == ActionType.Attacking && target.gameObject.GetComponent<SwordHitbox>().actionType == ActionType.Parrying){
Debug.Log("Attack hits parry");
if(transform.parent.gameObject.tag == playerTag){
Debug.Log("Enemy parries player");
transform.parent.gameObject.GetComponent<Parried>().GetParried(); //this version works!!
}
}
if(actionType == ActionType.Parrying && target.gameObject.GetComponent<SwordHitbox>().actionType == ActionType.Attacking){
// if(transform.parent.gameObject.tag == enemyTag){ //commented out while trying to fix target issue
Debug.Log("Parry hits Attack"); //shows in the console log
target.transform.parent.gameObject.GetComponent<EnemyParried>().GetParried(); //this version doesn't work!!
// }
}
}
}
The last two lines are where the problem is. When the enemy parries the player on line ten it works fine but when the player parries the enemy i get the message below, which is making me feel that the last line's dot walking trail isn't correct and it's trying to refer to the object of the parent rather than the instance.
NullReferenceException: Object reference not set to an instance of an object SwordHitbox.OnCollisionEnter2D (UnityEngine.Collision2D target) (at Assets/Toolkit/PlayerTools/Scripts/Items/SwordHitbox.cs:31)
The use of target dot walking works fine when referring to the instance itself (see line 3). I've tried several permutations of the dot walk including GetComponentInParent but have had no joy. Can anyone make any suggestions as to where i'm going wrong? Thanks in advance.