EASY! my spawn gameobjects in random area is Not working.

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);
		}
	}

2 Answers

2

I have no idea how could this work, Start() function is only called once, after the instance of script is instantiated.

Put your code in seperate function like:

public GameObject SpawnAtRandomPosition(GameObject prefabToSpawn){
             Vector3 position =  new Vector3(Random.Range(-10.0f, 10.0f), 0, Random.Range(-10.0f, 10.0f));
             return Instantiate(prefab, position, Quaternion.identity);
}

I understand you are creating a coroutine in some other script for this ? Thats unnecessary complicated, you can make easy condition in Update() …

private float nextSpawnTime = 0f;

void Update(){
if(Time.time > nextSpawnTime ){
SpawnAtRandomPosition(prefab);
SpawnAtRandomPosition(prefab);
nextSpawnTime = Time.time + 3f;
}
}

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

Look at the performance tracker and optimize your pathfinding. It should not be affecting your game this much.