简体   繁体   English

在运行时在Unity中创建类实例

[英]Creating Class instances in Unity at runtime

I want to create X objects in a loop, access and set properties of newly created objects. 我想在循环中创建X对象,访问和设置新创建的对象的属性。 I've used the Instantiate method with a passed RigidBody, like shown in the tutorial, but I need to access the properties of the script connected to the object, not just it's rigid body. 我已经将Instantiate方法与传递的RigidBody一起使用,如教程中所示,但是我需要访问连接到对象的脚本的属性,而不仅仅是它的刚体。

Here's the method I'm trying to make work: 这是我正在努力工作的方法:

public void makeGrid(int w = 10, int h = 10)
{
    gridWidth = w;
    gridHeight = h;

    int tileArrayLength = gridWidth * gridHeight;
    tileArray = new Tile[tileArrayLength];

    for (int i = 0; i < gridWidth; i++)
    {
        for (int j = 0; j < gridHeight; j++)
        {
            // add tiles
            Tile t = new Tile(); // !!! doesn't work >_<
            t.posX = i;
            t.posY = j;
            t.id = j + 10 * i;

            tileArray[t.id] = t;
        }
    }

}

I want to create X objects in a loop, access and set properties of newly created objects. 我想在循环中创建X对象,访问和设置新创建的对象的属性。

You can create prefabs through the editor and then instantiate them, or explicitely create a GameObject and attach the components you need to it: 您可以通过编辑器创建预制件然后实例化它们,或者明确地创建一个GameObject并附加您需要的组件:

GameObject prefabInstance = GameObject.Instantiate(Resource.Load("path_to_prefab")) as GameObject;

GameObject instanceThroughReference = GameObject.Instantiate(aReferenceToAnInstantiableObject) as GameObject;

GameObject emptyGameObject= new GameObject("empty game object");

For what concern: 出于什么问题:

I've used the Instantiate method with a passed RigidBody, like shown in the tutorial, but I need to access the properties of the script connected to the object, not just it's rigid body. 我已经将Instantiate方法与传递的RigidBody一起使用,如教程中所示,但是我需要访问连接到对象的脚本的属性,而不仅仅是它的刚体。

With property I think you mean Components attached to the GameObject instantiate. 对于属性我认为你的意思是附加到GameObject实例化的Components Either if you instantiate an object from a reference or loading through Resources.Load , if the original GameObject has the Component you want attached to it you can retrieve them using GetComponent method, or catching the return value of AddComponent. 如果您从引用实例化对象或通过Resources.Load加载,如果原始GameObject具有您想要附加到它的Component,则可以使用GetComponent方法检索它们,或者捕获AddComponent的返回值。

If you are creating an empty GameObject you have to attach explicitely the Components you need: 如果要创建一个空的GameObject ,则必须明确附加所需的Components

GameObject go = new GameObject("foo");
Bar bar = go.AddComponent<Bar>(); //where Bar extends MonoBehavior

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM