2015-10-11 55 views
0

嘿傢伙我有我的代碼問題,我無法弄清楚,我試圖讓它如此,當玩家與門碰撞或觸摸它它播放動畫。問題是動畫根本無法播放。不知道爲什麼門不會打開

還請記住,門腳本連接到門上。

using UnityEngine; 

using System.Collections; 

public class DoorOpen : MonoBehaviour 
{ 

    //this variable will decide wether door is open or not, its initially on false because the door is closed. 

    bool isDoorOpen = false; 

    //this variable will play the audio when the door opens 
    public AudioSource sound01; 

    void Start() 
    { 

    } 
    void OnCollisionEnter(Collision col) 
    { 
     if (col.gameObject.name == "Bathroom_Door" && Input.GetKeyDown(KeyCode.F)) 
     { 
      GetComponent<Animation>().Play("DoorO"); 
      sound01.Play(); 
      //this variable becomes true because the door is open 
      isDoorOpen = true; 
     } 
    } 
    // Update is called once per frame 
    void Update() 
    { 

    } 
} 
+0

舒爾它是'DoorO'?你是不是指'Door0'? – joe

+0

是的,我檢查了它。我的代碼有問題嗎? – DialUp

+0

它現在設置的方式必須在同一幀中按下F鍵,OnCollisionEnter事件纔會生成,因此門並不總是打開。 – ColmanJ

回答

1

您應該檢查更新中的GetKeyDown並在玩家進入碰撞盒時打開門。另一種選擇是使用OnCollisionStay而不是OnCollisionEnter,因爲OnCollisionEnter只在碰撞開始時調用一次。

public class DoorOpen : MonoBehaviour 
{ 

//this variable will decide wether door is open or not, its initially on false because the door is closed. 

bool isDoorOpen = false; 
bool canOpenDoor = false; 

//this variable will play the audio when the door opens 
public AudioSource sound01; 

void Start() 
{ 

} 
void OnCollisionEnter(Collision col) 
{ 
    if (col.gameObject.name == "Bathroom_Door") 
    { 
     canOpenDoor = true; 
    } 
} 
void OnCollisionExit(Collision col) 
{ 
    if (col.gameObject.name == "Bathroom_Door") 
    { 
     canOpenDoor = false; 
    } 
} 
// Update is called once per frame 
void Update() 
{ 
    if (canOpenDoor && Input.GetKeyDown(KeyCode.F)) 
    { 
     GetComponent<Animation>().Play("DoorO"); 
     sound01.Play(); 
     //this variable becomes true because the door is open 
     isDoorOpen = true; 
    } 
} 
} 
+0

嘿,我想要感謝一堆重建我的代碼並努力編輯它。雖然它沒有奏效,但門沒有打開,我把腳本指向主攝像頭,第一人稱控制器和它自己的門。我需要一個剛體或什麼東西? – DialUp

+0

劇本應該附在門上,並且門上應該有一個碰撞器供OnCollision觸發。你需要用OnCollision做的事情是在碰撞機上運行,​​以便觸發。爲了解決這個問題,你需要使用OnTrigger方法並使用設置爲觸發的碰撞器。 – ColmanJ

+0

好吧,我的門已經有一個對撞機,但我會添加另一個。 – DialUp

相關問題