- Home /
Question by
EnishanTopuz · Nov 14, 2021 at 05:23 PM ·
untiy3d
is there a way to make it so that they can spawn at random times 1 by 1
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class newSpawner : MonoBehaviour { public int numObjects = 10; public GameObject prefab;
void Start()
{
Vector3 center = transform.position;
for (int i = 0; i < numObjects; i++)
{
Vector3 pos = RandomCircle(center, 20.0f);
Quaternion rot = Quaternion.FromToRotation(Vector3.forward, center - pos);
Instantiate(prefab, pos, rot);
}
}
Vector3 RandomCircle(Vector3 center, float radius)
{
float value;
value = Random.value * 360;
Vector3 pos;
pos.x = center.x + radius * Mathf.Sin(value * Mathf.Deg2Rad);
value = Random.value * 360;
pos.y = center.y + radius * Mathf.Cos(value * Mathf.Deg2Rad);
value = Random.value * 360;
pos.z = center.z + radius * Mathf.Sin(value * Mathf.Deg2Rad);
return pos;
}
}
Comment
Answer by Kona · Nov 14, 2021 at 05:42 PM
public float maxSpawnDelay = 3f; //Max delay until next spawn in seconds
public float minSpawnDelay = 1f; //Min delay until next spawn in seconds
private bool _spawning; //Determine if spawn sequence is active
private float _lastSpawn; //Last time a prefab spawned
private float _curDelay; //Current delay in seconds until a spawn should occur
private int _curIndex; //Amount of objects spawned
void Start(){
_curDelay = Random.Range( minSpawnDelay, maxSpawnDelay ); //Get a new delay for next spawn
_lastSpawn = Time.time; //Cache time when begun
_spawning = true; //Starts the spawn sequence
}
//Progress the spawn sequence, should be called every time the prefab is instantiated
void OnSpawned() {
_curIndex++;
_lastSpawn = Time.time;
_curDelay = Random.Range( minSpawnDelay, maxSpawnDelay );
}
void Update() {
if( !_spawning ) {
return; //Stop if spawn sequence is not active
}
if( Time.time - _lastSpawn >= _curDelay ) { //When enough time has passed spawn a new prefab instance
Vector3 pos = RandomCircle( transform.position, 20f );
Quaternion rot = Quaternion.FromToRotation( Vector3.forward, center - pos);
Instantiate( prefab, pos, rot );
OnSpawned();
}
if( _curIndex >= numObjects ) {
_spawning = false; //Stop spawn sequence when the target number of objects has been instantiated
}
}
One, of multiple ways to achieve this. :)
Your answer
Follow this Question
Related Questions
Can't find some functions like 'OnParticleCollision'. 1 Answer
Detect mouse collision over an object 0 Answers
Refrencing Monobehaviour in the Editor 3 Answers
Handle vr content on android created by using unity 3D ? 0 Answers
Queue animations 0 Answers