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 instantiate object in the specific time?

Discussion in 'Scripting' started by faisalrahman, Sep 21, 2020.

  1. faisalrahman

    faisalrahman

    Joined:
    Feb 3, 2019
    Posts:
    9
    Hi, does anyone here know how to instantiate a gameobject at a certain time?
    for the example I have 2 object (Object A and Object B), I want to instantiate Object A at the 5 second, and I want to instantiate Object B at the 10 second in the position of Object A and destroy or disable Object A.
     
  2. Terraya

    Terraya

    Joined:
    Mar 8, 2018
    Posts:
    646
    Hey, there are tons of ways todo that,
    one example would be:
    Code (CSharp):
    1. private float timer = 5;
    2. private GameObject tempPrefab;
    3.  
    4. void Start() {
    5. StartCoroutine(testEnumerator(timer));
    6. }
    7.  
    8. private IEnumerator testEnumerator(float delay) {
    9.  
    10. while(true) {
    11.   if(tempPrefab) {
    12.       Destroy(tempPrefab);
    13.   }
    14.   tempPrefab = Instantiate(tempPrefab, position, rotation);
    15.   yield return new WaitForSeconds(delay);
    16. }
    17. }
    i codet that in the browser, expect a typo or something :) ,
    also i recommend to edit the Code and make it more flexible as it is only one example on how archieve what you described
     
  3. faisalrahman

    faisalrahman

    Joined:
    Feb 3, 2019
    Posts:
    9
    Thank you for your advice, but how if I want to Instantiate two objects in turn? For example I have 3object, The first object is the object that I gave the script, then at the 5th second I want to instantiate the second object and deactivate the first object, and on the 10th second I want to instantiate the 3rd object and deactivate or destroy the first and second objects?
    I'm new in c# script, and If you know how to do that, I really appreciate that :)