HarrisonO
HarrisonO

Reputation: 17

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

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

Answers (2)

YouCanCallMe Syarif
YouCanCallMe Syarif

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

Pranav Mehta
Pranav Mehta

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

Related Questions