Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question pls help me. i need the object to spawn after a set amount of time infinitely

Discussion in 'Editor & General Support' started by Epic263, Nov 17, 2022.

  1. Epic263

    Epic263

    Joined:
    Nov 17, 2022
    Posts:
    3
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class spawn : MonoBehaviour
    6. {
    7.  
    8.     public GameObject enemyPrefab;
    9.     // Update is called once per frame
    10.  
    11.     void Update()
    12.     {
    13.        
    14.         IEnumerator waiter()
    15.         {
    16.             Instantiate(enemyPrefab,transform.position, Quaternion.identity);
    17.             yield return new WaitForSeconds(5);
    18.            
    19.         }
    20.    
    21.     }
    22. }
    23.  
     
  2. Epic263

    Epic263

    Joined:
    Nov 17, 2022
    Posts:
    3
    i tried some stuff out but it didnt work pls help
     
  3. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    20,956
    Your code is defining the coroutine (specifically as a sub-method of the Update() method which can lead to problems so you shouldn't do that) but is missing two critical parts: (a) it needs to be started or it will not do anything, and (b) if it isn't looping it will only execute once.

    Code (csharp):
    1. using UnityEngine;
    2.  
    3. public class Spawn : MonoBehaviour
    4. {
    5.     public float delay = 5.0f;
    6.  
    7.     void Start()
    8.     {
    9.         StartCoroutine(Spawn);
    10.     }
    11.  
    12.     IEnumerator Spawn()
    13.     {
    14.         while (true)
    15.         {
    16.             yield return new WaitForSeconds(delay);
    17.             Instantiate(enemyPrefab,transform.position, Quaternion.identity);
    18.         }
    19.     }
    20. }
    Edit: Fixed error mentioned below.
     
    Last edited: Nov 18, 2022
    Epic263 likes this.
  4. Epic263

    Epic263

    Joined:
    Nov 17, 2022
    Posts:
    3
    Thanks broski