Skip to main content

Indie game storeFree gamesFun gamesHorror games
Game developmentAssetsComics
SalesBundles
Jobs
TagsGame Engines

Make spawnTime and spawnDelay random

A topic by kulix17 created Mar 20, 2022 Views: 256 Replies: 1
Viewing posts 1 to 3

Hi there, im complete noob to unity and i dont know how to make my 2 floats "spawnTime" and "spawnDelay" random. here is the script


using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class SpawnEnemyScript : MonoBehaviour

{

    public GameObject spawnee;

    public static bool stopSpawning;

    public float spawnTime;

    public float spawnDelay;

    // Start is called before the first frame update

    void Start()

    {

        stopSpawning = false;

        InvokeRepeating("SpawnObject", spawnTime, spawnDelay);

    }

    public void SpawnObject()

    {

        Instantiate(spawnee, transform.position, transform.rotation);

        if (stopSpawning)

        {

            CancelInvoke("SpawnObject");

        }

    }

}

Moderator moved this topic to General Development
(1 edit)

You may want to look into Random.Range - https://docs.unity3d.com/ScriptReference/Random.Range.html

An example: spawnTime = Random.Range(1, 5); (This means, a random number will be generated that will range from 1 to 5, and assign it to spawnTime variable)

I'm not sure how the code would work depending on the game you're making, but if you're planning to have different spawnTime/spawnDelay values every after instantiation of an object, you can put the code just below the Instantiate() function call.