2017-10-16 40 views
0

我想在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"); 

但只要我儘量控制預製的位置,我得到了幾個錯誤:

enter image description here

我只是不正確地傳遞參數?我究竟做錯了什麼?這實際上可能嗎?我已經習慣了在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

回答

3

你得到的錯誤,因爲沒有提供正確的參數來實例化功能。 Awesome想法閱讀doc

這是什麼樣子:

Instantiate(Object original, Vector3 position, Quaternion rotation); 

這是你要使用它的方式:那是因爲xPosyPos都是floats

Instantiate(Object original, float position, float rotation); 

。您需要將它們都轉換爲Vector3,然後將它傳遞給Instantiate函數。

這應該工作:

public void loadObject(string objReference, float xPos, float yPos) 
{ 
    Vector3 tempVec = new Vector3(xPos, yPos, 0); 
    Instantiate(Resources.Load<GameObject>(objReference), tempVec, Quaternion.identity); 

    //I want access to the prefabs properties 
} 

另外,如果你需要訪問實例化的預製屬性,你需要得到Instantiate函數返回的對象,並將其存儲到一個臨時變量:

public void loadObject(string objReference, float xPos, float yPos) 
{ 
    Vector3 tempVec = new Vector3(xPos, yPos, 0); 
    GameObject obj = Instantiate(Resources.Load<GameObject>(objReference), tempVec, Quaternion.identity); 

    //I want access to the prefabs properties 
    Debug.Log(obj.transform.position); 

    string val = obj.GetComponent<YourScriptName>().yourPropertyName; 
    obj.GetComponent<YourScriptName>().yourFunctionName(); 
}