销毁克隆点击

时间:2019-07-08 05:23:39

标签: c# unity3d instantiation destroy

我目前已经尝试了两天,用鼠标单击破坏实例化的预制克隆。

下面的代码做了两件事,在设定的间隔后会自动销毁它们,效果很好。单击功能会破坏所有克隆,即使我不单击预制件也不是我想要的。

更新:该项目处于二维状态

我已经在这里进行搜索,并在其他脚本平台上询问了其他人,他们的建议似乎无济​​于事。

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;

 public class DestroyOnClick : MonoBehaviour
 {
     public float lifeTime = 10f;


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

         if (lifeTime > 0)
         {
             lifeTime -= Time.deltaTime;
             if(lifeTime <= 0)
             {
                 Destruction();
             }
         }


     }


     void Destruction()
     {
         Destroy(this.gameObject);
     }
 }

3 个答案:

答案 0 :(得分:1)

让您的Monobehaviour实现PointerClick或PointerDown事件处理程序,并确保场景中有EventSystem,活动摄像机中有光线投射器。

//something along these lines:
using UnityEngine;
public class DestroyOnClick : Monobehaviour, IPointerClickHandler
{
    public void OnPointerClick(PointerClickEventData data)
    {
        Destroy(this.gameObject);
    }
}

答案 1 :(得分:0)

因为更新将运行所有游戏对象,所以请勿在更新中使用Input.GetMouseButton(0)

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;

 public class DestroyOnClick : MonoBehaviour
 {
     public float lifeTime = 10f;


     void Update()
     {
         if (lifeTime > 0)
         {
             lifeTime -= Time.deltaTime;
             if(lifeTime <= 0)
             {
                 Destruction();
             }
         }


     }
     //write here , it only work in this gameobject
     void OnMouseDown() { Destruction(); }

     void Destruction()
     {
         Destroy(this.gameObject);
     }
 }

答案 2 :(得分:0)

一种快速的解决方案是将对撞机放置在您要破坏的克隆上,然后在克隆上放置新脚本(或修改克隆上已有的脚本)。

脚本必须包含此方法:

private void OnMouseDown()
{
    Destroy(gameObject);
}

private void OnMouseUp()
{
    Destroy(gameObject);
}

这两种方法都将破坏被单击的GameObject,但它们将在单击的不同阶段执行。当您按下鼠标按钮时,将调用OnMouseDown(),而当您

时,将调用OnMouseUp