- Home /
Avoiding instantiating two things in same location?
I'm currently using Javascript to procedurally generate an in-game level. Unfortunately, for whatever reason, even though the code detects that it is going to place an object in the same location as another object, it continues the instantiation instead of instantiating an object that wouldn't interfere. The particular snippet of my code is below, where cursor and bcheck are both Vector3 objects while buildid is the id number for each object that can be instantiated.
while (onum > 0)
{
buildid = Random.Range(0,4);
if (buildid == 0)
{
if (prev == 2)
continue;
bcheck.z = bcheck.z + builddistance;
for (var i : int = 0; i < locs.length; i++)
{
if (bcheck == locs[i])
{
//How do I get the code to go back and generate a different buildid?--------------------
Debug.Log('True');
buildid = Random.Range(0,4);
bcheck.z = bcheck.z - builddistance;
continue;
//--------------------------------------------------------------------------------------
}
}
Instantiate(hallfor, cursor, Quaternion.identity);
cursor.z = cursor.z + builddistance;
bcheck = cursor;
locs.Push(cursor);
prev = 1;
onum = onum - 1;
}...
Answer by MicroGSD · Aug 07, 2013 at 08:13 AM
Are you trying to continue to the next while loop with that continue command in the for loop? If so it will only continue the for loop not the while loop.
If it enters the if statement (bcheck == locs[i]), does that mean it needs to try for a new buildid? If so, you could either use a boolean to mark it as a dupe.
Like so (sorry to mix up C# with JS):
bool bDirty = false;
for (var i : int = 0; i < locs.length; i++){
if (bcheck == locs[i]){
bDirty = true; //Set dirty to true
break; //Break out of for loop, dupe found
}
}
if(bDirty){ continue; }
Alternatively you could use a goto statement or encase the for loop in another while loop that runs into no dupes are found.
Yep! I changed the continue command to a break and added the boolean to the code like you described, but in Javascript. Thanks.
Your answer
Follow this Question
Related Questions
Instantiate object in for loop with array 2 Answers
Help with my Flocking Algorithm 0 Answers
Multiple Fire Points 2 Answers
Applying different textures to spawned objects. 2 Answers
Array won't be filled by Instantiate 1 Answer