i want to spawn only 2 of these gameobjects every 3 seconds , but my script is not working at first it was spawning hundreds immediately ,now im getting errors,
please help
2d game c#
using UnityEngine;
using System.Collections;
public class sss : MonoBehaviour
{
public GameObject prefab;
IEnumerator Example() {
print (Time.time);
yield return new WaitForSeconds (3);
print (Time.time);
}
// Instantiate the prefab somewhere between -10.0 and 10.0 on the x-z plane
void Start()
{
Vector3 position = new Vector3(Random.Range(-10.0f, 10.0f), 0, Random.Range(-10.0f, 10.0f));
Instantiate(prefab, position, Quaternion.identity);
}
}
The proper way (or let met say easiest because you can use Instantiate) to do this is to use InvokeRepeating not Instantiate - like so
using UnityEngine;
using System.Collections;
public class sss : MonoBehaviour
{
public GameObject prefab;
public float spawnFrequency = 3.0f; // 3 seconds
void Start()
{
if (prefab != null)
{
InvokeRepeating("SpawnItem", 0, spawnFrequency);
}
}
void SpawnItem()
{
// Instantiate the prefab somewhere between -10.0 and 10.0 on the x-z plane
Vector3 position = new Vector3(Random.Range(-10.0f, 10.0f), 0, Random.Range(-10.0f, 10.0f));
Instantiate(prefab, position, Quaternion.identity);
}
}
This answers your question. If you try to tweak this and end up breaking it then you will need to create a different question asking why your modified version does not work.
thanks movna but its still spawning tons of them I need it to spawn just 2 every 3 seconds I have tried to tweak the code but cant get it to work I tried adjusting the frequency but nothing it spawns so many that my scene keeps freezing form the rush of spawns I tried adjusting and correcting the code but its still spawning tons
thanks movna but its still spawning tons of them I need it to spawn just 2 every 3 seconds I have tried to tweak the code but cant get it to work I tried adjusting the frequency but nothing it spawns so many that my scene keeps freezing form the rush of spawns I tried adjusting and correcting the code but its still spawning tons
– sid4Look at the performance tracker and optimize your pathfinding. It should not be affecting your game this much.
– ShadyProductions