所以我试图通过我的PTick变量每3秒增加一次总资源我尝试通过IEnumerator使用它并在start方法中调用它但它只运行一次所以我在更新中尝试了它并且它运行为尽可能快。我有什么方法可以让它每隔3秒运行一次。我很高兴尝试替代方案,只要我能让它每3秒运行一次。
这是我正在努力工作的剧本
using UnityEngine;
using System.Collections;
public class Resources : MonoBehaviour {
private int foodPtick;
private int PowerPtick;
private int HappinessPtick;
private int MoneyPtick;
private int PopulationPtick;
public int foodTotal;
public int PowerTotal;
public int HappinessTotal;
public int MoneyTotal;
public int PopulationTotal;
void Start () {
StartCoroutine(ResourceTickOver(3.0f));
}
void Update () {
}
IEnumerator ResourceTickOver(float waitTime){
yield return new WaitForSeconds(waitTime);
foodTotal += foodPtick;
PowerTotal += PowerPtick;
HappinessTotal += HappinessPtick;
MoneyTotal += MoneyPtick;
PopulationTotal += PopulationPtick;
Debug.Log("Resources" + "food" + foodTotal + "power" + PowerTotal + "Happiness" + HappinessTotal + "Money" + MoneyTotal + "Population" + PopulationTotal);
}
public void ChangeResource(int food,int power, int happy, int money,int pop)
{
Debug.Log("Old Per Tick" + "food" + foodPtick + "power" + PowerPtick + "Happiness" + HappinessPtick + "Money" + MoneyPtick + "Power" + PopulationPtick);
foodPtick += food;
PowerPtick += power;
HappinessPtick += happy;
MoneyPtick += money;
PopulationPtick += pop;
Debug.Log("New Per Tick" + "food" + foodPtick + "power" + PowerPtick + "Happiness" + HappinessPtick + "Money" + MoneyPtick + "Power" + PopulationPtick);
}
答案 0 :(得分:1)
使用协程的第一种方式:
void Start () {
StartCoroutine(ResourceTickOver(3.0f));
}
IEnumerator ResourceTickOver(float waitTime){
while(true){
yield return new WaitForSeconds(waitTime);
foodTotal += foodPtick;
PowerTotal += PowerPtick;
HappinessTotal += HappinessPtick;
MoneyTotal += MoneyPtick;
PopulationTotal += PopulationPtick;
Debug.Log("Resources" + "food" + foodTotal + "power" + PowerTotal + "Happiness" + HappinessTotal + "Money" + MoneyTotal + "Population" + PopulationTotal);
}
}
使用Update的第二种方式:
void Update(){
timer += Time.deltaTime;
if(timer > waitTime){
timer = 0f;
foodTotal += foodPtick;
PowerTotal += PowerPtick;
HappinessTotal += HappinessPtick;
MoneyTotal += MoneyPtick;
PopulationTotal += PopulationPtick;
Debug.Log("Resources" + "food" + foodTotal + "power" + PowerTotal + "Happiness" + HappinessTotal + "Money" + MoneyTotal + "Population" + PopulationTotal);
}
}
使用InvokeRepeating的第三种方式:
void Start(){
InvokeRepeating("Method", 3f, 3f);
}
void Method(){
foodTotal += foodPtick;
PowerTotal += PowerPtick;
HappinessTotal += HappinessPtick;
MoneyTotal += MoneyPtick;
PopulationTotal += PopulationPtick;
Debug.Log("Resources" + "food" + foodTotal + "power" + PowerTotal + "Happiness" + HappinessTotal + "Money" + MoneyTotal + "Population" + PopulationTotal);
}
答案 1 :(得分:1)
在“开始”中调用它后,看起来你并没有让你的Coroutine保持活力。对StartCoroutine的调用将执行一次然后返回,因此如果没有某种循环,您将只能调用一个协程体。
将yield语句包含在循环中将为每个指定的waitTime提供一次迭代。在下面的示例中,您可以看到控制台每3秒记录一次时间戳更新。
Model A belongsToMany Model B