Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

how to instantiate object after time

Discussion in 'Scripting' started by azurecodes, May 22, 2021.

  1. azurecodes

    azurecodes

    Joined:
    Apr 29, 2021
    Posts:
    33
    hi, so I have a script that destroys an object and instantiates a new one. However, I want to wait for a delay and then replace the instantiated object with a new one. I have made some code like this, but it doesn't work. Am I doing some stuff wrong? Thanks,
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class DestroyObject : MonoBehaviour
    6. {
    7.  
    8.  
    9.     public GameObject destroyedVersion;
    10.     public GameObject newVersion;
    11.  
    12.      void OnMouseDown()
    13.     {
    14.         Instantiate(destroyedVersion, transform.position, transform.rotation);
    15.         Destroy(gameObject);
    16.         StartCoroutine(ExecuteTime(3f);
    17. }
    18.         IEnumerator ExecuteTime(float time)
    19.         {
    20.             yield return new WaitForSeconds(time);
    21.             Instantiate(newVersion, transform.position, transform.rotation);
    22.             Destroy(gameObject);
    23.         }
    24.     }
    25.  
    26. }
    27.  
     
  2. mishakozlov74

    mishakozlov74

    Joined:
    Aug 8, 2018
    Posts:
    133
    What exactly doesn't work? I can guess that destroying gameObject as 15 line stops all running coroutines too.
     
  3. azurecodes

    azurecodes

    Joined:
    Apr 29, 2021
    Posts:
    33
    oh, is there any way I can be able to destroy the game object and not obstruct the coroutines
     
  4. mishakozlov74

    mishakozlov74

    Joined:
    Aug 8, 2018
    Posts:
    133
    Well, i'd write a manager for these objects which can handle this behaviour.
     
  5. thesupersoup

    thesupersoup

    Joined:
    Nov 27, 2017
    Posts:
    70
    Yeah, what he said. It sort of sounds like you're implementing object pooling(?). Why destroy the object? You could have a coroutine that disables any visual components like meshes and colliders, reposition in the interim if desired, then reenable/refresh stats/what have you.
     
  6. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,762