0
\$\begingroup\$

In my demo I have a GUI where the user determines the number of AI that will spawn. I would like these AI to spawn onto the walkable area of my Grid. So I choose a random position then get the node from that, then check to see if the node is walkable, if it is then instantiate the game object at that position, however my problem here is that if it is not walkable I would like a new random position to be chosen and then checked again to see if it is walkable all the while looping until the number of game objects specified have been created. How do I go about the last part of this? I can't get my head around the logic.

        for(int i = 0; i < intBlinkyCount; i++)
                {

                    Vector3 pos = new Vector3(Random.Range(-(floatGroundScaleX/2*10), floatGroundScaleX/2*10), 0.5f, Random.Range(-(floatGroundScaleZ/2*10), floatGroundScaleZ/2*10));
                    Node randomNode = grid.NodeFromWorldPoint(pos);

                    if(randomNode.walkable)
                        {
                            Instantiate(blinky, pos, Quaternion.identity);
                            blinky.name = "blinky"+i;

                        }
                    else
                        {

                        }


                }
\$\endgroup\$
1
\$\begingroup\$

That seems like a very basic task, if I understood correctly. Obviously, if one node can fit only one blinky, then your function has to satisfy the following condition: Amount of blinkies <= amount of nodes.

And there're several ways to loop until you have placed a blinky. One would be just decrementing the iterating variable:

if(randomNode.walkable)
{ ... }
else {
  i--
}

Another one would be having a while loop instead of an if-conditional:

while(!randomNode.walkable) {
  //Choose a new random node here
}
//Instantiate your blinky here

Originally I had the second example as while-else, but I guess that statement doesn't work in C#.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Thanks for that, i've been staring at this for ages, head is fried! Went with your while loop, just couldn't get it straight in my head, ty \$\endgroup\$ – CH99 Mar 30 '15 at 12:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.