有太多原因你的代碼不能正常工作。你正在倒退。您的協同程序開始立即當您的程序啓動時,因爲wait()
從Start()函數被調用。當它開始時,它暫停3秒,並將你的GameObject設置爲SetActive(true)
;
如果您的GameObject已經可以在屏幕上看到,您的代碼將不會執行任何操作,因爲即使在可見時也會調用SetActive(true)
。如果您在3秒鐘之前未按/點擊屏幕,您將無法看到SetActive(true)
;因爲在那段時間你的協程代碼已經完成了。
此外,如果你禁用一個遊戲對象,它所附帶的協程將停止。該解決方案是創建遊戲對象想要的參考到禁用然後使用參考到禁用和使從另一個腳本沒有問題。
由於提供了一個代碼,我爲你修復/重寫了它。我用更強大的東西取代了OnMouseDown功能。
所有你需要做的是創建一個空的遊戲對象。 附加這個腳本到那個空GameObject。然後拖和下降是遊戲物體要禁用和使在這個「遊戲對象要禁用」 插槽在這個腳本,從編輯。
做不重視這個腳本到遊戲物體要禁用和使。
測試與立方體,它的工作。
using UnityEngine;
using System.Collections;
public class ALITEST: MonoBehaviour
{
//Reference to the GameObject you want to Disable/Enable
//Drag the Object you want to disable here(From the Editor)
public GameObject gameObjectToDisable;
void Start()
{
}
void Update()
{
//Keep checking if mouse is pressed
checkMouseClick();
}
//Code that checks when the mouse is pressed down(Replaces OnMouseDown function)
void checkMouseClick()
{
//Check if mouse button is pressed
if (Input.GetMouseButtonDown(0))
{
RaycastHit hitInfo = new RaycastHit();
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo))
{
//Check if the object clicked is that object
if (hitInfo.collider.gameObject == gameObjectToDisable)
{
Debug.Log("Cube hit");
StartCoroutine(wait()); //Call the function to Enable/Disable stuff
}
}
}
}
//This value is used to make sure that the coroutine is not called again while is it already running(fixes many bugs too)
private bool isRunning = false;
IEnumerator wait(float secondsToWait = 3)
{
//Exit coroutine while it is already running
if (isRunning)
{
yield break; //Exit
}
isRunning = true;
//Exit coroutine if gameObjectToDisable is not assigned/null
if (gameObjectToDisable == null)
{
Debug.Log("GAME OBJECT NOT ATTACHED");
isRunning = false;
yield break; //Exit
}
gameObjectToDisable.SetActive(false);
//Wait for x amount of Seconds
yield return new WaitForSeconds(secondsToWait);
//Exit coroutine if gameObjectToDisable is not assigned/null
if (gameObjectToDisable == null)
{
Debug.Log("GAME OBJECT NOT ATTACHED");
isRunning = false;
yield break; //Exit
}
gameObjectToDisable.SetActive(true);
isRunning = false;
}
}
我不能感謝你纔好。這個答案實際上解決了我的其他幾個問題 – ali10gaucho
歡迎您 – Programmer
一個非常慷慨的答案 – Fattie