【发布时间】:2018-06-20 08:28:57
【问题描述】:
我正在 Unity 中创建一个弹出菜单选项。现在我的问题是我在 void update 中制作的协程被调用了很多次。我的意思是在我的 Unity 控制台上,Debug.Logs 正在递增。它不应该是正确的,因为它已经是协程的。可以帮助我了解更多协程并帮助我解决我的小问题。
这是我的代码:
[SerializeField]
GameObject Option;
[SerializeField]
Button btn,btn2;
[SerializeField]
GameObject open, close;
[SerializeField]
GameObject[] opt;
bool startFinding = false;
void Start()
{
Option.SetActive(false);
Button popUp = btn.GetComponent<Button>();
Button popUp2 = btn2.GetComponent<Button>();
popUp.onClick.AddListener(PopUpOption);
popUp2.onClick.AddListener(ClosePopUp);
}
void Update()
{
if (startFinding)
{
StartCoroutine(GameOptions());
}
}
IEnumerator GameOptions()
{
//Get All the tags
opt = GameObject.FindGameObjectsWithTag("MobileOptions");
if (opt[0].GetComponent<Toggle>().isOn == true && opt[1].GetComponent<Toggle>().isOn == true)
{
Debug.Log("Disable first the check box then choose only 1 option between" + "'rendering'"+ "and" + "'livestreaming'");
}
//Livestreaming
if (opt[0].GetComponent<Toggle>().isOn == true)
{
Debug.Log("Livestreaming Activate");
} else
{
Debug.Log("Livestreaming Deactivate");
}
//Rendering
if (opt[1].GetComponent<Toggle>().isOn == true)
{
Debug.Log("Rendering Activate");
} else
{
Debug.Log("Rendering Deactivate");
}
//Fog
if (opt[2].GetComponent<Toggle>().isOn == true)
{
Debug.Log("Fog Activated");
} else
{
Debug.Log("Fog Deactivated");
}
//Camera Effect
if (opt[3].GetComponent<Toggle>().isOn == true)
{
Debug.Log("Camera Effect Activated");
} else {
Debug.Log("Camera Effect Deactivated");
}
yield return null;
}
void PopUpOption()
{
startFinding = true;
//Disable The Mobile Option Button
open.SetActive(false);
//Enable the Close Option Button
close.SetActive(true);
//activate the Mobile Options
Option.SetActive(true);
}
void ClosePopUp()
{
startFinding = false;
//eanble the mobile option button
open.SetActive(true);
//disable the close option button
close.SetActive(false);
//deactivate the Mobile Option
Option.SetActive(false);
}
【问题讨论】:
-
据我所知,代码完全按照您的要求执行。当然,
Update()方法会被重复调用。在该方法中,只要将startFinding字段设置为true,就可以启动协同程序。因此,一旦显示弹出窗口,我绝对希望您的协同程序会启动多次(通常,Update()方法每秒调用数十次)。如果您不希望它继续启动,那么...不要继续启动它! -
说了这么多,不清楚你为什么首先把它作为一个协程......它有一个直通的执行路径,没有任何类型的循环,通常会在一个协同程序。
-
哦,你是说先生这是正常的,因为它在我的更新功能上??
-
“这很正常,因为它在我的更新功能上?” -- 是的,“正常”,因为这正是你编写的代码要做的事情.我不知道你打算做什么,所以我不能说这是否正确(你的问题表明它不是),但不知道你为什么选择编写协程首先,以及您期望它如何工作,不可能提出一个可以解决您的问题的实际答案。
-
“你的意思是它有一个直通的执行路径,没有任何通常会在协同程序中找到的循环”——有没有循环语句,例如
while、for、foreach等。在 Unityd3 中,协程从被调用到第一个yield return执行,此时控制权返回给调用者。然后控制在调用者(在枚举器上调用MoveNext(),但这在这里并不重要)的控制下恢复,紧跟yield return。您的方法只产生一次,然后就完成了。非典型的协同程序。
标签: c# arrays unity3d coroutine