This code randomly spawns objects and then destroy them after some wait. what I want to do is to make sure the random spawned object is not spawned at previously spawned object such as it spawns above it. How may I do that?
public IEnumerator Spawn () {
yield return new WaitForSeconds (2.0f);
counting = true;
while (timeLeft > 0 && gameOver==false)
{
GameObject ball = balls [Random.Range (0, balls.Length)];
Vector3 spawnPosition = new Vector3 ( Random.Range (-maxWidth, maxWidth), Random.Range (-maxHeight, maxHeight), 0.0f);
Quaternion spawnRotation = Quaternion.identity;
GameObject ballClone = (GameObject) Instantiate (ball, spawnPosition, spawnRotation);
StartCoroutine (DestroyAfterWait (ballClone));
yield return new WaitForSeconds (Random.Range (1.0f, 2.0f));
}
//yield return new WaitForSeconds (2.0f);
GameOver ();
}
Put the Balls in a List and check if the spawnPosition is closer to it than the size of the ball.
using System.Collections.Generic;
private List<GameObject> spawnedBalls = new List<GameObject>();
public IEnumerator Spawn () {
yield return new WaitForSeconds (2.0f);
counting = true;
while (timeLeft > 0 && gameOver==false)
{
MakeClean();
Vector spawnPosition = GetSpawnPosition();
if(spawnPosition != Vector3.zero)
{
Quaternion spawnRotation = Quaternion.identity;
GameObject ballClone = (GameObject) Instantiate (ball, spawnPosition, spawnRotation);
spawnedPositions.Add(ballClone);
StartCoroutine (DestroyAfterWait (ballClone));
}
yield return new WaitForSeconds (Random.Range (1.0f, 2.0f));
}
//yield return new WaitForSeconds (2.0f);
GameOver ();
}
void MakeClean()
{
while(!CleanUpList())
{
CleanUpList();
}
}
bool CleanUpList()
{
foreach(GameObject ball in spawnedBalls)
{
if(ball != null)
continue;
else
{
spawnedBalls.Remove(ball);
return false;
}
}
return true;
}
Vector3 GetSpawnPosition()
{
GameObject ball = balls [Random.Range (0, balls.Length)];
Vector3 spawnPosition = new Vector3 ( Random.Range (-maxWidth, maxWidth), Random.Range (-maxHeight, maxHeight), 0.0f);
float sizeOfBall = 1.0f;
foreach(GameObject ball in spawnedBalls)
{
if(Vector3.Distance(ball.transform.position, spawnPosition) <= sizeOfBall)
{
return Vector3.zero;
}
}
return spawnPosition;
}
Code is untested but i hope you get the idea. I noticed comparing Vectors is much faster than using Physics in large projects so i started to use this approach more often in my projects. (That was in Unity4, not sure about U5). So GetSpawnPosition either returns Vector3.zero or if the position was fine a valid Vector3.