2016-02-19 59 views
0

我試圖讓玩家按下按鈕時傳送帶扭轉方向。用GetComponent C編輯變量#

下面是傳送帶

using UnityEngine; 
using System.Collections; 

public class Conveyor : MonoBehaviour { 
    public float speed = 1.0f; 

    void OnTriggerStay(Collider col) 
    { 
     col.transform.position += transform.forward * speed * Time.deltaTime; 
    } 
} 

的代碼和按鈕的代碼

public class PushButton : MonoBehaviour 
{ 
    public GameObject Button; 

    private Conveyor conveyor; 

    void Awake() 
    { 
     conveyor = GetComponent<Conveyor>(); 
    } 

    void OnTriggerStay(Collider entity) 
    { 
     if (entity.tag == "Player") 
     { 
      if (Input.GetKeyUp(KeyCode.E)) 
      { 
       conveyor.speed = conveyor.speed * -1; 
      } 
     } 
    } 
} 

我得到一個錯誤說「對象未設置爲一個對象按鈕的實例.OnTriggerStay(Unity Engine.Collider實體)(在Assests/PushButton.cs21)

我還不是很熟悉使用getComponent,所以我不知道如何解決這個問題。不勝感激。

+0

注意「public GameObject Button」變量必須是小寫字母,所以它會是「按鈕」。另外請注意,Unity中有一個叫做「Button」的東西,所以你可能不會使用它。例如,將其稱爲「topLeftRedButton」 – Fattie

回答

0

GetComponent將需要對初始化對象和對象已分配的組件或類的引用。對於你想要的東西,你會想在場景中找到一個遊戲對象。由於您已指定您的GameObject具有分配給它的Conveyor類,因此請找到您的GameObject,然後指定Conveyor組件。

void Awake() 
{ 
conveyor = GameObject.FindWithTag("Conveyor").GetComponent<Conveyor>(); 
} 

這應該做的竅門,等待你用'Conveyor'標籤標記你的Conveyor遊戲對象。

然而,甚至更​​簡單的方式快速「搶」這樣的事情。但要小心!

void Awake() 
{ 
conveyor = Object.FindObjectOfType<Conveyor>(); 
// ONLY DO THAT IF THERE IS ONLY >>ONE<< OF THE THING! 
} 

這是一篇小文章。 http://answers.unity3d.com/answers/46285/view.html

你經常這樣做,例如找到「老闆」對象..場景管理員等。

不要忘了,你總是可以用使用一個公共變量,然後拖動inteh Inspector--這對於初學Unity的人來說總是一個好主意。