首页 > 解决方案 > 如何在一定时间后删除我的克隆对象?

问题描述

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

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#unity3d

解决方案


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

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);
    }

推荐阅读