- Home /
Question by
unity_R0Zoro · Apr 04, 2020 at 05:41 AM ·
randomspawnrandom.rangerangespawner
How To Random Range a Float?
I want to make the spawn time and spawn delay a random number between 1 and 5 whenever the game starts. In the picture below I need to adjust it myself.
![using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spawners : MonoBehaviour
{
public GameObject Spawn;
public bool stopSpawning = false;
public float spawnTime;
public float spawnDelay;
void Start()
{
InvokeRepeating("SpawnObject", spawnTime, spawnDelay);
}
public void SpawnObject()
{
Instantiate(Spawn, transform.position, transform.rotation);
if (stopSpawning)
{
CancelInvoke("SpawnObject");
}
}
}][1]
untitled.png
(103.1 kB)
Comment
Best Answer
Answer by spencerz · Apr 04, 2020 at 05:56 AM
public void SpawnObject()
{
spawnTime = Random.Range(1.0f, 5.0f);
spawnDelay = Random.Range(1.0f, 5.0f);
Instantiate(Spawn, transform.position, transform.rotation);
if (stopSpawning)
{
CancelInvoke("SpawnObject");
}
}
Put this in your SpawnObject () method.
Answer by n_rusev · Apr 04, 2020 at 05:50 AM
Hello. If you want to generate random numbers when the game starts you can use Unity's Random class in your Start method. For example:
void Start()
{
spawnTime = Random.Range(1f,5f);
spawnDelay = Random.Range(1f,5f);
InvokeRepeating("SpawnObject", spawnTime, spawnDelay);
}
It is part of UnityEngine, so you don't need to include new libraries.