我正在尝试使用Unity3d创建类似jig-saw拼图的游戏 我有两个gameObj,每个都有空的父gameObj,当我把它们(childObj)拖到彼此时它们互相粘在一起。我将两个ParentObj合并为一个,它有两个孩子(piece1 piece2)。如何将PolygonCollider2D从piece1和piece2添加到ParentObj?
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");
}
}
}
}
答案 0 :(得分:1)
您可以使用GameObject.AddComponent
将组件添加到GameObject。
你可以做到
piece1.parent.gameObject.AddComponent<PolygonCollider2D>();
此函数还返回组件本身,如Unity文档中所述: http://docs.unity3d.com/ScriptReference/GameObject.AddComponent.html