Collision detection on child gameobjects

Hi ! I am currently making a 2d platformer. I have my player which is a gameobject made of out a cube then inside the player i have another gameobject which is also a gameobject.

I am trying to detect a collision of the child gameobject within the code i added on the player itself.

Sure it’s possible, but it would be a lot easier if you put scripts on them. You can even put scripts on children dynamically.

If you wanted to do it without child scripts, you would simply iterate over your children and then do a raycast on their collider with the screen point to ray.

However, if you wanted to let unity handle it, and do dynamic child scripts, here’s one (slightly advanced) way to go about doing it.

Parent class:

void Awake()
{
    foreach( Transform childTransform in transform )
    {
        ChildClass childClass = childTransform.AddComponent<ChildClass>();
        childClass.TouchDelegate = OnTouchedChild;
    }
}
 
void OnTouchedChild( GameObject childObject )
{
    Debug.Log( "touched child " + childObject.name, childObject );
    // do whatever
}

Child class (let’s say it’s called ChildClass, but you can name it whatever as long as it’s updated in the parent class script):

public delegate void OnTouchedDelegate( GameObject touchedObject );
 
OnTouchedDelegate touchDelegate;
public OnTouchDelegate TouchDelegate
{
    set { touchDelegate = value; }
}
 
void OnMouseDown() // monobehaviour method
{
   touchDelegate( gameObject );
}

You might want to put some error handling in there, like maybe check to see if the touch delegate is not null if that’s a case you want to handle, or if the child object has a collider before adding the script, or whatever your specific needs are