2017-10-16 83 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(); 
}