Hi, so I have this code that starts a Coroutine which contains a for loop. When it gets to that part of the code, instead of looping as many times as specified, it goes through only once. Basically what I want is to highlight a piece then wait 2 seconds then remove it from the game. If I make it a void instead of IEnumerator and remove the waitforseconds it loops normally. In the code below it is supposed to loop 15 times. Can anybody help me?
public int squares;
void Start()
{
squares = 20;
}
void Update()
{
StartCoroutine(Leave5Pieces());
}
IEnumerator Leave5Pieces()
{
piecesToRemove = squares - 5;
for (int i = 0; i < piecesToRemove; i++)
{
GameObject [] pieces = GameObject.FindGameObjectsWithTag("Square");
pieces*.GetComponent<Renderer>().material.color = selectedColor;*
yield return new WaitForSeconds(2);
GameObject.Destroy(pieces*);*
}
}
Some problems here!
First. You’re starting the coroutine every single frame! You should move that StartCoroutine to Start() or somewhere where it’ll just fire when you want it to.
The next problem is that you can’t be sure the index will be in the collection returned by FindGameObjectsWithTag.
Hi @flaviusxvii and @Rajeesh_AR . Thank you very much for the replies! I made a change on the code but it still not working as I need. I created a bool canPlay to use in the Update to start the coroutine if it’s the PC turn, as @flaviusxvii said. This variable is set to true by another script that I have. And I also changed the For loop to the If statement that @Rajeesh_AR said. The following problems happened: As the quantity of squares is recalculated every time the PC canPlay by the method RefreshVariables(), when I call the coroutine after destroying a piece, the number of squares is recalculated, so the If Statement does not leave me with 5 pieces. I need this refresh method due to counting that I make in other script.
Another problem that occured was that the color only changed on the first piece, the others were simply removed after the seconds.
Do you guys know what is happening? Why the For loop doesn’t loop? I think this loop would be a great solution once the squares wouldn’t be recalculated inside the loop.
int i =0;
void Start()
{
squares = 20;
}
void Update()
{
RefreshVariables();
if (canPlay)
{
StartCoroutine(Leave5Pieces());
}
}
IEnumerator Leave5Pieces()
{
piecesToRemove = squares - 5;
if (i < piecesToRemove )
{
print(piecesToRemove);
GameObject [] pieces = GameObject.FindGameObjectsWithTag("Square");
pieces*.GetComponent<Renderer>().material.color = selectedColor;*
yield return new WaitForSeconds(2);
GameObject.Destroy(pieces*);*
StartCoroutine(Leave5Pieces());
i++;
}
}
Just to finish I used the print() to see if it gives any clue. The output was this :
15, 15, 14, 13, 12 , 11 .