2017-10-13 47 views
0

我有ñGameObjects这是母亲的孩子GameObject让孩子游戏对象摧毁本身问题

每个孩子都附有自己的孩子脚本。如果我点击一个孩子对象,全部孩子回应。

当孩子被加载时,它将把自己置于父母之下,并且我还传递一个数字,以便稍后如果需要时可以跟上。

这是我的脚本。真的没有太多。任何人都知道我在做什么错了?

public GameObject parentGameObject; 
public int childIndex; 

void Start() { 
    transform.parent = parentGameObject.transform; 
} 

void Update() { 
    if (Input.GetMouseButton(0)) { 
     Die(); 
    } 
} 

public void Die() { 
    Debug.Log("Child " + this.childIndex + " clicked"); 
    Destroy(this.gameObject); 
} 
+2

你在更新功能检查代码,如果你点击鼠标按钮没有,如果你点击一个游戏对象:

,如果你是2D,但它的例子是,像这样目前尚不清楚。所以他们都回应是正常的。 – CNuts

+0

我想我很困惑@CNuts我需要知道什么时候单击鼠标按钮。 'Die()'包含游戏对象。 –

+0

ryeMoss的答案几乎是你应该这样做的。 – CNuts

回答

2

由于这个脚本被附加到所有子对象,它们都被检查,看是否被点击鼠标,因此所有当检测到鼠标点击(因为在每次检测到一个鼠标点击毁灭自己脚本)。

我会建议在母亲gameobject中使用Raycast并附加Colliders并标记每个孩子检测其中一个单击时,然后销毁相应的单击的对象的一个​​脚本。

void Update() 
{ 
    if (Input.GetMouseButtonDown(0)) 
    { 
     // cast a ray at the mouses position into the screen and get information of the object the ray passes through 
     RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero); 
     if (hit.collider != null && hit.collider.tag == "child") //each child object is tagged as "child" 
     { 
      Destroy(hit.collider.gameObject); 
     } 
    } 
}