Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
2 captures
13 Jun 22 - 14 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by Mrroundtree22 · Sep 23, 2021 at 01:57 AM · listloopforeach

foreach loop problem

 public class TEST : MonoBehaviour {
 
     public List<int> numbers = new List<int>() { 1, 2, 3 };
 
     public void Update()
     {
         if (Input.GetKeyDown(KeyCode.Space))
         {
             Test();
         }
     }
 
     public void Test()
     {
         foreach (int number in numbers)
         {
             Debug.Log(number);
         }
     }
 }

Currently when I press the spacebar all the numbers appear in the console. What I want to happen is that only one number appear in the console I.e if I press spacebar once then the console says 1, if I press spacebar again then the console says 2 and finally when I press it a third time it says 3.

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
1
Best Answer

Answer by AlgoUnity · Sep 23, 2021 at 03:30 AM

      public class TEST : MonoBehaviour {
  
      public List<int> numbers = new List<int>() { 1, 2, 3 };
      public int nextNumber = 0;
  
      public void Update()
      {
          if (Input.GetKeyDown(KeyCode.Space))
          {
              Test();
          }
      }
  
      public void Test()
      {
           Debug.Log(numbers[nextNumber]);
           nextNumber = (nextNumber + 1) % numbers.Length; //bring nextNumber back to 0 at the end
      }
  }
Comment
Add comment · Show 8 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Mrroundtree22 · Sep 23, 2021 at 01:03 PM 0
Share

*Count not Length But other than that it works perfectly. Thank you!

avatar image Mrroundtree22 · Sep 25, 2021 at 01:37 AM 0
Share

Actually I was wondering if there's a way to keep the foreach loop?

avatar image AlgoUnity Mrroundtree22 · Sep 25, 2021 at 03:36 AM 0
Share

The game runs at 60 frames per second, Update() is called 60 times per second, and will do everything inside it within that frame. You can't pause the function in the middle and continue on the next update. If you absolutely have to do that, look up Coroutines on google, which are a bit more complicated, but they are not so bad. Definitely a few steps up from what you are doing here though.

avatar image Eno-Khaon Mrroundtree22 · Sep 25, 2021 at 04:02 AM 2
Share

While you conceivably *could* maintain the foreach() loop, it would be terribly cumbersome (and, if the List<> were to change contents partway through the loop, potentially less predictable than a regular for() loop alternative).

For proof of concept, here's an example of keeping the foreach() loop, but I can't say I would *ever* recommend its use, because it's needlessly bulky in practice:

 public KeyCode triggerKey = KeyCode.Space;
 private bool trigger = false;

 void Start()
 {
     StartCoroutine(Test());
 }

 void Update()
 {
     if(Input.GetKeyDown(triggerKey))
     {
         TestTrigger();
     }
 }

 IEnumerator Test()
 {
     foreach(int number in numbers)
     {
         // Loop here until triggered, when it will leave the loop
         // and repeat on the next foreach() entry
         while(!trigger)
         {
             yield return null;
         }
         trigger = false;
         Debug.Log(number);
     }
     // Since this script is untested, I forget whether
     // it's actually necessary to guarantee a yield on all
     // paths of an IEnumerator function, so this is here
     // as a safety net
     yield return null;
 }
 
 void TestTrigger()
 {
     trigger = true;
 }
avatar image Bunny83 Eno-Khaon · Sep 25, 2021 at 06:58 AM 0
Share

Right, but instead of using that bool variable you can directly check the input in the coroutine

 public KeyCode triggerKey = KeyCode.Space;

 void Start()
 {
     StartCoroutine(Test());
 }
 
 IEnumerator Test()
 {
     foreach(int number in numbers)
     {
         while(!Input.GetKeyDown(triggerKey))
         {
             yield return null;
         }
         Debug.Log(number);
     }
  }

This actually has the additional benefit once the coroutine has finished, there's no overhead anymore since we don't need the update method at all. Of course if you want to repeat the loop once it ran through, you can wrap the foreach loop in an endless while loop

Show more comments

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

130 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

InvalidOperationException Collection was modified; 3 Answers

How to have a loop run itself again if returned value is a known exception, with a new return value. 1 Answer

A node in a childnode? 1 Answer

String taken from a JSON file is not being Queued 1 Answer

Item not being taked off from the List 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges