Check if condition for all elements inside an array is true

I've a C# Array typed Transform object in Unity3D. To win the game all pictures rotation.z value must be 0.

Transform[] Pictures;

if (Pictures[0].rotation.z == 0 &&
    Pictures[1].rotation.z == 0 &&
    Pictures[2].rotation.z == 0 &&
    Pictures[3].rotation.z == 0 &&
    Pictures[4].rotation.z == 0 &&
    Pictures[5].rotation.z == 0)
{
    YouWin = true;
    //WinText.enabled = true;//.SetActive(true);
    int currentSceneIndex = SceneManager.GetActiveScene().buildIndex;
    SceneManager.LoadScene(currentSceneIndex + 1);
}

But this is ugly way. And if the array expands, the game does not end. So i tried to write new codes to make things easier. But couldn't.

foreach (var item in Pictures)
{
    if (item.rotation.z == 0)
    {
        YouWin = true;
        int currentSceneIndex = SceneManager.GetActiveScene().buildIndex;
        SceneManager.LoadScene(currentSceneIndex + 1);
    }
}

foreach is not working well. Exists from foreach at first image. Must check every images rotation.z value.

for (int i = 0; i < Pictures.Length; i++)
{
    if (Pictures[i].rotation.z ==0)
    {
        YouWin = true;
        int currentSceneIndex = SceneManager.GetActiveScene().buildIndex;
        SceneManager.LoadScene(currentSceneIndex + 1);
    }
}

"for" also same result with foreach. I think its requires nested for or foreach. How can i check all items if their rotation.z value equals to 0? Thank you.

Upvotes: 1

Views: 3870

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186833

To win the game all pictures rotation.z value must be 0.

Let's implement it with a help of Linq All:

 using System.Linq;

 ...

 if (Pictures.All(picture => picture.rotation.z == 0)) {
   // Win 
   YouWin = true;

   int currentSceneIndex = SceneManager.GetActiveScene().buildIndex;
   SceneManager.LoadScene(currentSceneIndex + 1);
 }

If you wan to loop you can invert logic - YouWin == true if we don't have counter example (item.rotation.z != 0)

 // we win... 
 YouWin = true;

 foreach (var item in Pictures) 
   if (item.rotation.z != 0) {
      // ... unless we don't win
      YouWin = false;

      break;
   }

 if (YouWin) {
   // Win 
   int currentSceneIndex = SceneManager.GetActiveScene().buildIndex;
   SceneManager.LoadScene(currentSceneIndex + 1);
 } 

Upvotes: 5

Willie
Willie

Reputation: 382

You have several options to perform this task. The simplest is to add an extra flag and negate the checking condition. If any pictures rotation.z is not 0, you have not won. If all pictures rotation.z is 0, you have won.

bool success = true;
foreach (var item in Pictures)
{
    if (item.rotation.z != 0)
    {
        success = false;
    }
}
if (success) {
    YouWin = true;
    int currentSceneIndex = SceneManager.GetActiveScene().buildIndex;
    SceneManager.LoadScene(currentSceneIndex + 1);
}

Or using Linq:

bool won = pictures.TrueForAll(x=> x.rotation.z == 0);

Upvotes: 2

Related Questions