当前位置:   article > 正文

【Unity 3D】C#中while do while for foreach等循环语句的讲解(附测试代码)_unity while循环

unity while循环

1:while循环

只要给定的条件为真 C#语言中的while循环语句会重复执行代码块的语句 语法如下

  1. while(condition){
  2. statement(s);
  3. }

测试代码如下

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class Test_8_5 : MonoBehaviour
  5. {
  6. void Start()
  7. {
  8. /* 局部变量定义 */
  9. int a = 10;
  10. /* while 循环执行 */
  11. while (a < 20)
  12. {
  13. Debug.Log("a 的值:" + a);
  14. a++;
  15. }
  16. }
  17. }

2:do while循环

for循环和while循环是在循环的头部判断循环条件,而do while循环是在循环的尾部判读循环条件,do while循环与while循环类似 但是do while循环会确保至少执行一次循环

do{

statement(s);

}

while(condition);

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class Test_8_6 : MonoBehaviour
  5. {
  6. void Start()
  7. {
  8. /* 局部变量定义 */
  9. int a = 10;
  10. /* do 循环执行 */
  11. do
  12. {
  13. Debug.Log("a 的值:" + a);
  14. a = a + 1;
  15. } while (a < 20);
  16. }
  17. }

 3:for循环

for循环是一个特定次数的循环的重复控制结构

for(init;condition;increment){

statement(s);}

测试代码如下

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class Test_8_7 : MonoBehaviour
  5. {
  6. void Start()
  7. {
  8. /* for 循环执行 */
  9. for (int a = 10; a < 20; a++)
  10. {
  11. Debug.Log("a 的值:" + a);
  12. }
  13. }
  14. }

4:foreach循环

C#语言也支持foreach循环,使用foreach循环可以迭代数组或一个集合对象

测试代码如下

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class Test_8_8 : MonoBehaviour
  5. {
  6. void Start()
  7. {
  8. // foreach循环
  9. int[] fibarray = new int[] { 0, 8, 13 };
  10. foreach (int element in fibarray)
  11. {
  12. Debug.Log(element);
  13. }
  14. // for 循环
  15. for (int i = 0; i < fibarray.Length; i++)
  16. {
  17. Debug.Log(fibarray[i]);
  18. }
  19. // 设置集合中元素的计算器
  20. int count = 0;
  21. foreach (int element in fibarray)
  22. {
  23. count += 1;
  24. Debug.Log("元素 #" + count + ":" + element);
  25. }
  26. Debug.Log("数组中元素的数量: " + count);
  27. }
  28. }

创作不易 觉得有帮助请点赞关注收藏~~~

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/94368
推荐阅读
相关标签
  

闽ICP备14008679号