我想在C#中創建一個函數,它可以從我的預製文件夾中選擇一個預製件,將它添加到遊戲中,並允許我設置該預製件的屬性(如果需要)。該功能我現在有:Unity2D C# - 如何創建一個通用的預製實例化器?
public void loadObject(string objReference, float xPos, float yPos){
Instantiate(Resources.Load<GameObject>(objReference),xPos,yPos);
//I want access to the prefabs properties
}
我也可以調用函數從任何地方在我的課加載預製:
loadObject ("Prefab/BeamPlatform", this.transform.position.x, this.transform.position.y);
當這只是我傳遞給函數的字符串,它工作:
public void loadObject(string objReference){
Instantiate(Resources.Load<GameObject>(objReference));
}
//
loadObject ("Prefab/BeamPlatform");
但只要我儘量控制預製的位置,我得到了幾個錯誤:
我只是不正確地傳遞參數?我究竟做錯了什麼?這實際上可能嗎?我已經習慣了在AS3這樣做,這是一樣簡單:
public function loadObject(objClass, xPos:Number, yPos:Number){
var obj = new objClass();
obj.x = xPos;
obj.y = yPos;
obj.otherProperty = ;
}
我試圖避免設立一個類級別的變量並拖動到預製它的檢查。我覺得這會限制我的選擇,但我正在聽任何建議。
Here's what it looks like when it works with just a string passed