c# - 如何在一定时间后删除我的克隆对象?
问题描述
我是编程新手。我想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);
}
}
解决方案
销毁函数有一个可选的时间参数
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);
}
推荐阅读
- swiftui - SwiftUI:如何在 macOS 11 上设置工具栏的标题?
- javascript - 如果值存在于其他对象数组中,则替换数组的值
- flutter - Flutter 用数组做奇怪的事情
- excel - 只是一个基本的点击器,但不断出错
- python - 使用 bash 将整数传递给 python 脚本
- flutter - 为了解决 Flutter web 中缺少滚动条的想法
- angular - Angular 10 材质选项卡:根据路由参数选择选项卡?
- javascript - Typescript中的文本格式字符串?
- android - Spinner DatePicker 不会更改文本颜色
- audio - 音频卷积输出比输入长,当将数据反馈到固定长度的流时,我该如何解决这个问题?