- Home /
Problem with for infinitely looping
Hi, can someone help me with this for loop that is infinitely looping the engine when every time I press play, what's wrong with it? Thank you so much.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RigSystem : MonoBehaviour
{
[Header("Levels")]
[SerializeField] private GameObject gameSystem;
[SerializeField] private int rigLevel = 1;
private Material[] localMaterialLevel = new Material[12];
[Header("Rigs")]
[SerializeField] private GameObject objectColor;
[SerializeField] private GameObject fanColor;
private void Start()
{
for (int i = 1; i <= rigLevel; i++)
{
if (i == rigLevel)
{
objectColor.GetComponent<Renderer>().material = localMaterialLevel[(i -= 1)];
if (rigLevel < 5)
{
fanColor.GetComponent<Renderer>().material = localMaterialLevel[10];
}
else
{
fanColor.GetComponent<Renderer>().material = localMaterialLevel[11];
}
}
}
}
}
Answer by Bunny83 · Apr 17, 2021 at 05:05 PM
First of all your for loop it completely pointless since the only code that is inside the loop is executed when i == rigLebel. So why do you have a loop in the first place? Though your main issue is that you have an i -=1
inside your code. So you are manipulating your for loop variable. Which means you will get stuck at this value since when i == rigLevel you subract 1 from i and the for loop is adding 1 at each iteration. Therefore i will stay at that value and you never leave your loop.
As I said, what's the point of the for loop in the first place?
You could replace your Start method with
void Start()
{
objectColor.GetComponent<Renderer>().material = localMaterialLevel[rigLevel - 1];
if (rigLevel < 5)
{
fanColor.GetComponent<Renderer>().material = localMaterialLevel[10];
}
else
{
fanColor.GetComponent<Renderer>().material = localMaterialLevel[11];
}
}
This would have the same effect, just without the pointless loop. Though in general you should never change the loop variable inside the loop body. There are some rare situations where this may be neccessary, but you should be aware of the implications when you do so. In such a case it would be better to use a while loop instead.
Now I understand
I was thinking to add 10 if statements to check the level and asign the material depending of the level but as you say that is pointless and just putting it in the void Start has the same effect, I didn't realize that xD
Thank you so much
Your answer
Follow this Question
Related Questions
"for" loop - DrawTexture problem. 0 Answers
For loop C#? 2 Answers
Using for as while. 3 Answers
Shorten code with FOR loop 1 Answer