Reputation: 17
I am new to programming. I want to spawn punchAttack
from a prefab and then destroy it after a few seconds to remove clutter. Everything i have tried has made it so I can no longer instantiate any punch attacks after the destroy counter has reached 0. How can I delete each instance after it has been alive for 2 seconds?
Thanks in advance!
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);
}
}
Upvotes: 0
Views: 274
Reputation: 159
Maybe you can try with this
Gameobject g = Instantiate(punchAttack, transform.position, transform.rotation)as Gameobject;
Destroy(g, Yourdelaytime);
so your script wil be like this :
void Update()
{
if(Input.GetKeyDown(KeyCode.F))
{
Gameobject g = Instantiate(punchAttack, transform.position,
transform.rotation)as Gameobject;
Destroy(g, Yourdelaytime);
}
}
or you can make Destroy(gameobject,YourDelayTime)
on punchAttack prefab
with new Script
Upvotes: 0
Reputation: 144
Destroy function has one optional time parameter
Destroy(GameObject, time);
Use it like this
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);
}
Upvotes: 1