Search Unity

Detect collision of a child object with tag

Discussion in 'Scripting' started by Pavlos_Mavris, May 26, 2020.

  1. Pavlos_Mavris

    Pavlos_Mavris

    Joined:
    Sep 17, 2018
    Posts:
    57
    Hello everyone, I want to detect the collision of a child object, for example I have a player object(parent) and contains the child objects which are the parts of the player(head,arms,legs...). I want to detect for example if my spear hits the head object which is child object and if does hit the head my player will die. I try to do the obvious technic:

    Code (CSharp):
    1. if(collision.gameObject.tag == "Head")
    2.         {
    3.             Debug.Log("Enemy head");
    4.             FindObjectOfType<EnemyAI>().playerHealth -= 100;
    5.         }
    6.         else
    7.         {
    8.             FindObjectOfType<EnemyAI>().playerHealth -= 50;
    9.         }
    But it doesn't detect the tag.
    BTW the script is attached to the spear object.
     
  2. RasiFederico

    RasiFederico

    Joined:
    Jan 30, 2020
    Posts:
    6
    Make sure both spear and the head have a rigidbody component on it, even with "gravity = off" and "kinematic = on" , anddand try to write this "collision.transform.tag == Head" instead... (Or use the "CompareTag" that is better). if this doesn't work make the head a trigger and use the "void OnTriggerEnter()"

    Hope this help.
     
    FrankTheStud likes this.
  3. kshitijv

    kshitijv

    Joined:
    Nov 18, 2021
    Posts:
    9
    make sure that all your child's game objects have the tag that you are searching for and not the parent game object