2012-08-26 23 views
1

我正在使用C#腳本處理Unity中的項目。 GUI.Box將出現在屏幕的頂部。當玩家離開現場時,箱子將消失。在玩家離開指定地點後,如何讓這個盒子在那裏停留3秒?使GUI.Box停留3秒

Danpe的代碼修正(工作代碼):

bool shown = false; 

void OnGUI() { 
if (car.transform.position.y>=43 && car.transform.position.y<=44) 
{ 
    shown = true; 
} 
else if (shown) 
{ 
    StartCoroutine(DisapearBoxAfter(3.0f)); 
} 
if(shown) 
{ 
    GUI.Box(new Rect((Screen.width/2)-200,0,400,30) , "King of the hill"); 
} 
} 

IEnumerator DisapearBoxAfter(float waitTime) { 
// suspend execution for waitTime seconds 
yield return new WaitForSeconds(waitTime); 
shown = false; 
} 




void Update() { 
    OnGUI(); 
} 

回答

1
bool shown = false; 

void OnGUI() { 
    if (car.transform.position.y>=43 && car.transform.position.y<=44) 
    { 
     shown = true; 
    } 
    else if (shown) 
    { 
     StartCoroutine(DisapearBoxAfter(3.0)); 
    } 
    if(shown) { 
     GUI.Box(new Rect((Screen.width/2)-200,0,400,30) , "King of the hill"); 
    } 
} 

IEnumerator DisapearBoxAfter(float waitTime) { 
    // suspend execution for waitTime seconds 
    return yield WaitForSeconds (waitTime); 
    shown = false; 
} 


void Update() { 
    OnGUI(); 
} 
+0

嗨Danpe, 謝謝你的快速反應。您提供的代碼有一些錯誤,我使用調試器進行了更正,現在它可以正常工作。非常感謝。我將在我的問題中提供工作代碼。 – user1626227

+0

嗨,np我很樂意提供幫助,因爲我很久以前就遇到過這個問題:) 無論如何,如果它回答了你的問題,你可以勾選我的答案作爲問題的正確答案。 – Danpe

0
function Start() 
{ 
    ShowBox(); 
} 

function ShowBox() 
{ 
    // show label 
    show = true; 

    // cancel invoking method if already set to call after 3 seconds 
    CancelInvoke("HideBox"); 

    // will call HideBox() after 3 sec 
    Invoke ("HideBox", 3.0F); 
} 

function HideBox() 
{ 
    // dont show label 
    show = false; 
} 

function Update() 
{ 
    if (car.transform.position.y>=43 && car.transform.position.y<=44) 
    { 
     ShowBox(); 
    } 
} 

function OnGUI() 
{ 
    if(shown) 
    { 
      GUI.Box(new Rect((Screen.width/2)-200,0,400,30) , "King of the hill"); 
    } 
}