unity-game-engineunity-components

Get ?-type Collider from child, and add duplicate component to parent


I'm trying to get a Collider of unknown type from a child object at run-time and add an identical Collider to the parent. How can I do that? This is the best I've got so far, but doesn't work:

Collider MColl = GetComponentInChildren<Collider>();
gameObject.AddComponent<MColl.GetType>();

"Error: 'MColl' is a variable but is used like a type"


Solution

  • You almost had it right. Use this to get it to work:

    Collider collider = GetComponentInChildren<Collider>();
    gameObject.AddComponent(collider.GetType()); // Assigns e.g. BoxCollider.
    

    Good luck!