Home > Software engineering >  Trying to add a delay to an gameobject spawner
Trying to add a delay to an gameobject spawner

Time:11-03

I'm a new C# programmer here in the early stages of creating a project in Unity where you play as a microbe that needs to eat blue food pellets to grow and survive. I've got the blue food pellets to spawn randomly across the map but I want to add a delay because too much is spawning at once. This is what I've attempted to do so far. Any help would be appreciated!

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Threading.Tasks;

public class Spawner : MonoBehaviour
{
    public GameObject food;
    public async void Wait(float duration)
    {
        Vector3 randomSpawnPosition = new Vector3(Random.Range(-50, 50), 1, Random.Range(-50, 50));
        Instantiate(food, randomSpawnPosition, Quaternion.identity);
        await Task.Delay((int)duration * 1000);
    }
    // Update is called once per frame
    void Update()
    {
        async void Wait(float duration);


    }

    
}

What I've tried:

Putting the delay function in the update function. The program just gets confused and thinks I'm trying to call the function.

Calling the function after combining all my code into the one function, the program rejects this.

CodePudding user response:

Like the default code snippet says, Update runs every frame. Using Task.Delay to delay events would still spawn objects with the same frequency, they would only start spawning delayed.

The typical way to do this in Unity is to use a Assets, Hierarchy & Inspector

Hit play and you have a new spawn every X seconds where X is the value of delay in seconds.

Screenshot of the game executing after 21 seconds.

Screenshot

What does it do? Every frame it evaluates if can spawn a new pellet (bool canSpawnNewPellet). If it can, then it starts an invocation of another method with X seconds (and mark the bool as false since we don’t want to call more invocations during de instantiation of our first sample).

For more references: https://docs.unity3d.com/ScriptReference/MonoBehaviour.Invoke.html

Edited: typo.

  • Related