Home > Software design >  Instantiate then destroy and recall the function in Unity
Instantiate then destroy and recall the function in Unity

Time:09-10

    public GameObject laser;
    public Transform spawnPoint;
    private float Cooldown = 5f;
    private float cooldownTime = 5f;
    private bool spawned;
    private GameObject laserbeam;

    private void Start()
    {
        Cooldown = cooldownTime;
    }
    // Update is called once per frame
    void Update()
    {
        if (!spawned)
        {
            Cooldown -= Time.deltaTime;
        }
        if (Cooldown <= 0)
        {
            laserbeam = Instantiate(laser, spawnPoint.position, Quaternion.identity) as GameObject;
            Cooldown = cooldownTime;
            if (!spawned)
            {
                Cooldown -= Time.deltaTime;
                spawned = true;
            }   
        }
        if (spawned)
        {
            Destroy(laserbeam);
        }
    }
}

this the code and i need to fix the idea is i am trying to spawn a laserbeam the destroying after an amount of time the istantiating it like a obstacle

CodePudding user response:

Destroy has a second parameter for how long after it should be destroyed.

using

 Destroy(gameObject);

will destroy instantly.

using

 Destroy(gameObject, 1f);

will destroy the game object after 1 second.

Call destroy as soon as you create the laserbeam, and set the second param to how long it should be alive.

Scripting reference.

  • Related