- Home /
Problem with arrays and while loops
I've set up a grid of cubes with all random colors and am trying to check through them to ensure there are no cubes next to each other and then runs a function to go through and change them if there are more 3 cubes in a row but for some reason Unity stops responding when it tries to enforce 3 or less cubes.
void Start () {
...
bool checkColors = CheckColors ();
while (checkColors == true) {
RearrangeColors ();
}
}
bool CheckColors (){
Color colorColumnCheck = Color.red;
Color colorRowCheck = Color.red;
int colorColumnCount = 0;
int colorRowCount = 0;
bool matchingCubes = false;
for (int x = 0; x<gridWidth; x++) {
for (int y=0; y<gridHeight; y ++) {
if (colorColumnCheck == allCubes[x,y].GetComponent<Renderer> ().material.color){
colorColumnCount++;
}else{
colorColumnCount = 0;
}
if (colorColumnCount >= 2){
Debug.Log ("Found matching Vertically");
matchingCubes = true;
}
if (y == gridHeight - 1){
colorColumnCount = 0;
}
colorColumnCheck = allCubes[x,y].GetComponent<Renderer> ().material.color;
if (matchingCubes == true) {
return matchingCubes;
}
}
}
for (int y = 0; y<gridHeight; y++) {
for (int x = 0; x <gridWidth; x++) {
if (colorRowCheck == allCubes [x, y].GetComponent<Renderer> ().material.color) {
colorRowCount++;
}else{
colorRowCount = 0;
}
Debug.Log ("Found matching Horizontally");
if (colorRowCount >= 32) {
matchingCubes = true;
}
if (x == gridWidth - 1){
colorRowCount = 0;
}
colorRowCheck = allCubes [x, y].GetComponent<Renderer> ().material.color;
if (matchingCubes == true) {
return matchingCubes;
}
}
}
return matchingCubes;
}
So it seems to me, that Unity or C# in general doesn't reevaluate the variable using the function it was set to. so if it was true once it was always true. adding checkColors = CheckColors(); fixes it. so many lost hours for this. >_<
You're going to need to do some c# homework. A function is only called once. So checkcolors
will stay at whatever value it is given when you call it inside the Start()
function. If at breakfast I give you a banana, you don't get a banana as many times during the day as you want. Ins$$anonymous$$d you need to ask me to give you a banana whenever you want one. So just assume I am a function called banana()
.
Your answer
![](https://koobas.hobune.stream/wayback/20220613191934im_/https://answers.unity.com/themes/thub/images/avi.jpg)