Multiple spawning in the same place

Hey , can anyone help me with this problem . i want to spawn enemy at random point(defined by me ) without spawning at same place until spawn place enemy get destroy. here’s my code for this … any help will be appreciated.

void SpawnTarget()
{

    List <Transform>freespawnPoints = new List<Transform>(spawnPoints);
  	time = 0;
		if (freespawnPoints.Count <= 0)
            return; // Not enough spawn points
		
		// Find a random index between zero and one less than the number of spawn points.
		int spawnPointIndex = Random.Range (0, freespawnPoints.Count);

		Transform pos = freespawnPoints[spawnPointIndex];     
		freespawnPoints.RemoveAt(spawnPointIndex); // remove the spawnpoint from our temporary list

	// Create an instance of the enemy prefab at the randomly selected spawn point's position and rotation.
		Instantiate (prefab, pos.position, pos.rotation);

}

Where are you adding the spawnpoints to the list?

Try placing the RemoveAt() after the Instantiate().

The way you have it, just adds the spawnPoints each frame even if you removed them last frame, so first line shouldn't be there, maybe you could have it inside the Awake(). Now you need a link between the prefab and the spawnPoint from which it got spawned, when it gets destroyed you need to send a "message" from the prefab to your class to add that spawnPoint back to the list. There are several ways to do that. Hope that helps.

Good point. You would get an access violation in C++, I had that mixed up, sorry.

1 Answer

1

List <Transform>freespawnPoints = new List<Transform>(spawnPoints); is a local variable so when you do freespawnPoints.RemoveAt(spawnPointIndex); it has no effect.

You should have freespawnPoints be a class variable and note that when you do freespawnPoints = new List<Transform>(spawnPoints); you actually reset it, so what you want is to take a spawn point from it when you spawn an enemy and add that spawn point to it again whenever it’s made available again.