Creative Magic
Creative Magic

Reputation: 3141

Creating Class instances in Unity at runtime

I want to create X objects in a loop, access and set properties of newly created objects. 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.

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;
        }
    }

}

Upvotes: 0

Views: 7092

Answers (1)

Heisenbug
Heisenbug

Reputation: 39164

I want to create X objects in a loop, access and set properties of newly created objects.

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 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.

With property I think you mean Components attached to the GameObject instantiate. 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.

If you are creating an empty GameObject you have to attach explicitely the Components you need:

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

Upvotes: 2

Related Questions