0
我在Unity3D中製作了一個BreakOut克隆。我正在研究powerup和槳板之間的碰撞。 powerup有一個全局字符串'type',它決定了powerup的類型。它在實例化上電之後被分配。來自外部腳本的字符串變量在不應該時讀取null?
事情是,當我通過槳腳本中的OnCollisionEnter訪問這個變量時,它變成了null,用打印測試。但是,如果在實例化上電後打印該變量,則不會將其設置爲空。
任何人都可以爲我清除它嗎?這是我對槳對象的腳本代碼:
void OnCollisionEnter(Collision other)
{
if (other.gameObject.tag == "powerup")
{
if (other.gameObject.GetComponent<PowerUp>().type == "Wide")
{
print ("Wide PU!");
}
else if (other.gameObject.GetComponent<PowerUp>().type == "Split")
{
print ("Split PU!");
}
//Only the Else gets executed: the print() only displays 'Type: ', indicating the 'type' variable is null?
else print("Type: " + other.gameObject.GetComponent<PowerUp>().type);
Destroy(other.gameObject);
}
}
這是我對的上電對象的腳本代碼:
public string type;
// Use this for initialization
void Start() {
}
// Update is called once per frame
void Update() {
}
//This function acts as a class constructor.
//It may be called after Initializing this GameObject to set proper Power Up behavior.
public void Initialize(string type)
{
//Test the type string given when a brick breaks in BrickBreak script
switch (type)
{
case "Wide":
//If the type is 'wide', set proper graphical and logical settings
renderer.material.color = Color.red;
type = "Wide";
print ("Spawn Type: " + type); //This displays the type variable just fine!
break;
case "Split":
renderer.material.color = Color.green;
type = "Split";
print ("Spawn Type: " + type); //This displays the type variable just fine!
break;
default:
print ("No proper Power Up constructor string input!");
break;
}
}
你打電話給自己初始化?聽起來像是應該在醒來或開始時分配類型 – LearnCocos2D
事情是,當你在Unity中實例化一個GameObject時,你不能傳遞任何參數......就像標準C#中的構造函數一樣。因此,我做了一個自定義的Initialize函數,並在Instantiate()函數後立即調用它。即使它不在Start()或Awake()中,我在與槳發生碰撞之前調用該函數,所以它應該沒問題,對吧? – Turbosheep
是應該工作正常。雖然你應該考慮在這裏使用枚舉而不是字符串比較。 – LearnCocos2D