galvakojis
galvakojis

Reputation: 428

Child and parents relations Unity

I am trying to create game something like jig-saw puzzle with Unity3d I have two gameObj, each of them have empty Parent gameObj, when i am dragging them (childObj) to each other they stick to each other. I merge two ParentObj into one, which haves two childs(piece1 piece2). How add PolygonCollider2D to ParentObj from piece1 and piece2?

void CombinePieces(Transform piece1, Transform piece2) {

        if (piece1.parent != null) {
            //Debug.Log (piece1.parent.name);
                if (piece2.parent != null) {

                //Destroy(piece2.parent, 3.0f);
                }

                piece2.parent = piece1.parent;


                //here should be created new PolygonCollider2D which should have PolygonCollider2D  
                //from piece1 and piece2

                piece2.collider2D.enabled = false;
                piece1.collider2D.enabled = false;

            }

            else {

                if (piece2.parent != null) {
                    piece1.parent = piece2.parent;
                }

                else {

                    Transform trans = new GameObject().transform;

                    piece1.parent = trans;
                    piece2.parent = trans;
                Debug.Log("6");

                }
            }
        }
}

Upvotes: 0

Views: 251

Answers (1)

Ricardo Reiter
Ricardo Reiter

Reputation: 581

You can use GameObject.AddComponent to add a Component to a GameObject.

You can do
piece1.parent.gameObject.AddComponent<PolygonCollider2D>();

This function also returns the component itself, as explained in the Unity Documentation: http://docs.unity3d.com/ScriptReference/GameObject.AddComponent.html

Upvotes: 1

Related Questions