I have this spawning script in my game and you can buy more spawners from a shop. I would like to have the spawn delay be like if the delay is 1, spawning is slow and if it's 20 then the spawning would be faster. Is this even possible? Thanks!
IEnumerator PigSpawner (float spawnInterval, GameObject PigToSpawn) {
GameObject InstatiatedObject = Instantiate(PigToSpawn, new Vector3(Random.Range(bottomLeftWorld.x, topRightWorld.x), Random.Range(bottomLeftWorld.y, topRightWorld.y), 0), Quaternion.identity, Parent);
InstatiatedObject.GetComponent<Destroy>().enabled = true;
yield return new WaitForSeconds(spawnInterval);
StartCoroutine (PigSpawner (spawnInterval, PigToSpawn));
}
CodePudding user response:
// spawner script
public int spawnInterval = 1;
public GameObject enemy;
void Start()
{
while(true)
{
yield return new WaitForSeconds(spawnInterval);
Instantiate(enemy, transform.position, Quaternion.normalized);
}
}
EDIT: Thanks to a comment, I just realized that you're looking for a negative-feedback system where higher numbers make it faster. That can be done by just waiting 1/spawninterval
instead of spawninterval
. I've done that below, and replaced spawninterval with spawnspeed.
// spawner script
public int spawnSpeed = 1;
public GameObject enemy;
void Start()
{
while(true)
{
yield return new WaitForSeconds(1 / spawnSpeed);
Instantiate(enemy, transform.position, Quaternion.normalized);
}
}
CodePudding user response:
Something like this
IEnumerator PigSpawner(float spawnInterval, GameObject PigToSpawn)
{
while(true)
{
GameObject InstatiatedObject = Instantiate(PigToSpawn, new Vector3(Random.Range(bottomLeftWorld.x, topRightWorld.x), Random.Range(bottomLeftWorld.y, topRightWorld.y), 0), Quaternion.identity, Parent);
InstatiatedObject.GetComponent<Destroy>().enabled = true;
yield return new WaitForSeconds(spawnInterval);
}
}
Then you would want to call this with an inverse lerp to get that behaviour, like so
StartSpawner()
{
var spawnIntervalMagnitude = Mathf.InverseLerp(_minumumSpawnTimeValue, _maximumSpawnTimeValue, _spawnDelay);
var spawnInterval = _defaultSpawnInterval * spawnIntervalMagnitude;
StartCoroutine(PigSpawner(spawnInterval, _pigToSpawn));
}
In this example _minumumSpawnTimeValue
might be 1
and _maximumSpawnTimeValue
might be 20
. You will need a default spawn time, and then any value you set between 1, and 20 will be linearly interpolated between those values to give a bigger/smaller delay :-)