-
设计一个累计程序
-
每3秒钟计数+1
-
达到一个随机生成的上限时,累计停止
-
方法一:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CountLoop : MonoBehaviour
{
public int countNum = 0;
public int maxNum;
// Start is called before the first frame update
void Start()
{
maxNum = Random.Range(10, 15); // 设定计数上限
StartCoroutine(CountRoutine()); // 启动协程
}
// Update is called once per frame
void Update()
{
}
IEnumerator CountRoutine() // 设定协程
{
while (countNum < maxNum)
{
yield return new WaitForSeconds(3.0f); // 等待 3 秒
countNum++; // 计数+1
}
}
}
- 方法二:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CountLoop : MonoBehaviour
{
public int countNum = 0;
public int maxNum;
// Start is called before the first frame update
void Start()
{
maxNum = Random.Range(10, 15); // 设定计数上限
StartCoroutine(CountRoutine()); // 启动协程
}
// Update is called once per frame
void Update()
{
}
IEnumerator CountRoutine() // 设定协程
{
while (true)
{
yield return new WaitForSeconds(3.0f); // 等待 3 秒
countNum++; // 计数+1
if (countNum == maxNum) // 达到最大值跳出循环
{
break;
}
}
}
}