如何在一定时间后删除克隆的对象?

How can I delete my cloned object after a certain amount of time?

提问人:HarrisonO 提问时间:7/25/2020 更新时间:7/25/2020 访问量:147

问:

我是编程新手。我想从预制件生成,然后在几秒钟后销毁它以消除杂乱。我尝试过的一切都成功了,因此在破坏计数器达到 0 后,我无法再实例化任何拳头攻击。如何在每个实例处于活动状态 2 秒后将其删除? 提前致谢!punchAttack

using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Security.Cryptography;
using System.Threading.Tasks;
using UnityEngine;

public class PunchAttack : MonoBehaviour
{
    [SerializeField]
    private GameObject punchAttack;
    private GameObject cloneOb;
  
    

   
    void Update()
    {
        if(Input.GetKeyDown(KeyCode.F))
        {
            Instantiate(punchAttack, transform.position, transform.rotation);
            Task.Delay(10).ContinueWith(t => delete());
            
        }
    }
    void delete()
    {
        Destroy(gameObject);
    }
}

C# Unity-游戏引擎

评论


答:

1赞 Pranav Mehta 7/25/2020 #1

销毁函数有一个可选的时间参数

Destroy(GameObject, time);

像这样使用它

 void Update()
    {
        if(Input.GetKeyDown(KeyCode.F))
        {
            //save instantiated punchAttack object into a variable and pass it in delete function
            GameObject go = Instantiate(punchAttack, transform.position, transform.rotation);
            delete(go);
            
        }
    }
    void delete(GameObject go)
    {
        Destroy(gameObject, 2f);
    }
0赞 YouCanCallMe Syarif 7/25/2020 #2

也许你可以试试这个

Gameobject g = Instantiate(punchAttack, transform.position, transform.rotation)as Gameobject;

Destroy(g, Yourdelaytime);

所以你的脚本将是这样的:

void Update()
    {
        if(Input.GetKeyDown(KeyCode.F))
        {
            Gameobject g = Instantiate(punchAttack, transform.position, 
            transform.rotation)as Gameobject;

            Destroy(g, Yourdelaytime);
        }
    }
   

或者你可以用新的脚本来制作Destroy(gameobject,YourDelayTime)punchAttack prefab