- Home /
The question is answered, right answer was accepted
Check if all values in a list are equal
This is probably simple but I have just stared at it too long. I have a 4X4 grid of gems. the grid is laid out on the x-z axis, but the height of the gems vary on the Y axis. I have a function that, when a gem is clicked, moves the gem down 1 unit. It also moves neighboring gems up. The point is to get all the gems on the same level (Think a 3-D version of lights out) My problem is I cannot get the logic right to check if each gems Y position is equal. I have an empty gameObject that holds a list of the gems. I am trying to search through it, and check that a gems has the same height as the last gem. If so, keep going. THen at the end, if all were equal. Say you won!. But sometimes I win even when they are not equal. Here is the code. Please ask if more info is needed.
void Update ()
{
for(int i = 1;i<=gems.Count-1 ;i++)
{
//Debug.Log (gems.Count);
Gem currentGem = gems[i-1];
Gem nextGem = gems[i];
if(currentGem.transform.localPosition.y == nextGem.transform.localPosition.y && hasWon)
{
hasWon = true;
}
else{
hasWon = false;
}
if(i == gems.Count-1 && hasWon)
{
Debug.Log("You Win!");
}
hasWon=true;
}
}
Answer by SirCrazyNugget · Mar 06, 2014 at 11:33 PM
You should probably look at using a multidimensional array and storing them in the necessary XYZ addresses. That will allow you to check each type within the array rather than trying to depict where each one is.
//if you continue with it the way you have it, just determine the Y position of the first Gem
float posY = gems[0];
//then presume they've won until you find a gem that isn't in the right position
hasWon = true;
for (int i = 1; i < gems.Count; i++){
if(gems[i].transform.localPosition.y != posY){
hasWon = false;
}
}
//then determine after you've checked each one whether they've actually won and do something
if(hasWon){
//tada!
}
That's the ticket! And is what I thought I was trying to. Anyway, I only need to check the Y axis. The other x and z are irrelevant at this point. Also, the data is already contain in a list; one that is used because of its added functionality. I can alter the size, and add a remove components at will. There is also another list that stores what gem is next to each gem. This is how I will control the game logic when manipulating gems. ($$anonymous$$ove the gem up and the neighbors down, when a gem is clicked). Anyway, thanks for the proper game logic, I was struggling with this for a while. It happens when you stare at the same code for so long.
I did have to modify one thing.
float posY = gems[0].transform.localPosition.y
Follow this Question
Related Questions
Foreach with where with 2 lists 0 Answers
Brute Force Search Algorithm 0 Answers
False = true, what am I doing wrong? 2 Answers
Card/Tile Game, loops dont update element0 of playerHand properly 1 Answer
A node in a childnode? 1 Answer