How to put two game objects together and disable rigidbody on a child?

Hi Everybody,

I need to put two game objects together when they collide. So I have a player whith the only one script attached to. Then I have many Cubes tagged “Cube”. When cube1 touches cube2 I need cube2 to become a child of cube1 with rigidbody disabled on cube2.

How do I approach it?

What part are you having trouble with? Can you disable a rigidbody (isKinematic)? Can you give something a parent (easy)? Check for a collision (SMBL wrote that)? Worried about when 2 pairs of objects collide? Worried about "who wins" so they don't each try to become children of the other? It seems like this is still a design problem. Not to the "how do I do X" stage yet.

1 Answer

1

There is function OnCollisionEnter. On script of cube 1

void OnCollisionEnter(Collision coll) {
    GameObject cube2 = coll.gameObject

    cube2.SetParent(this.gameObject.transform);
    Destroy(cube2.GetComponent<Rigidbody>());
}

Yeah, but I have really many cubes to become children on collision. The script needs to be attached to the player or something else. Any cube that becomes a child must have rigidbody disabled/removed afterwards...

Each cube needs OnCollisionEnter if you want to use the built-in collision system. Unity's collision/physics system can only send collision events to the thing that hit. If a cube hits something, Unity sends that exact cube an OnCollisionEnter. There's no way to auto-redirect all hits to some other script.