- Home /
Question by
mevsvader · May 17, 2021 at 10:00 AM ·
instantiatepositioning
how do i keep repeating code till conditions are met so that the next part of the code can happen?
my code here is supposed to instantiate a cube randomly 1 unit left right up or down. but the spawn position (asteroidcore) keeps moving to already occupied spaces. i tryed to write code that would randomly move the spawnpos till there was nothing in its collider space and then it would instantiate a cube. but it doesnt work
IEnumerator keepgeneratingasteroid()
{
GameObject lastasteroid;
GameObject[] allasteroids = GameObject.FindGameObjectsWithTag("asteroid");
lastasteroid = allasteroids[allasteroids.Length-1];
while (true)
{
yield return new WaitForSeconds(.2f);
xminus1thru1 = Random.Range(-1, 1);
yminus1thru1 = Random.Range(-1, 1);
if (xminus1thru1 != 0)
{
yminus1thru1 = 0;
}
else if (yminus1thru1 != 0)
{
xminus1thru1 = 0;
}
asteroidcollider = Physics2D.OverlapBoxAll(asteroidcore.transform.position, new Vector2(1, 1), 0);
if (asteroidcollider.Length > 0)
{
repositioncore();
asteroidcollider = Physics2D.OverlapBoxAll(asteroidcore.transform.position, new Vector2(1, 1), 0);
}
Instantiate(asteroid, asteroidcore.transform.position, new Quaternion(0, 0, 0, 0));
}
void repositioncore()
{
xminus1thru1 = Random.Range(-1, 1);
yminus1thru1 = Random.Range(-1, 1);
if (xminus1thru1 != 0)
{
yminus1thru1 = 0;
}
else if (yminus1thru1 != 0)
{
xminus1thru1 = 0;
}
Vector3 lastasteroidoffset = new Vector3(lastasteroid.transform.position.x + xminus1thru1, lastasteroid.transform.position.y + yminus1thru1, 0);
asteroidcore.transform.position = lastasteroidoffset;
asteroidcollider = Physics2D.OverlapBoxAll(asteroidcore.transform.position, new Vector2(1, 1), 0);
Debug.Log("collider more than 0");
}
}
Comment
float timeEnd = Time.time + 3f;
bool stopRepeating = false;
while( stopRepeating==false )
{
yield return null;
Debug.Log("repeating something...");
if( Time.time > timeEnd ) stopRepeating = true;
}
Debug.Log("done repeating");