unity c# array of gameobjects code example

Example 1: unity array of gameobjects

If you want to create an array of this gameobject, you can do this as follows:

int Size = 10;     //Number of objects
GameObject[] Tiles = new GameObject[Size];
Let's assume you have created a prefab, called "Tile". If we want to initialize the array's gameobjects, we could do it like this:

//Loop for the entire size of the array, 10 in this case
for (int i = 0; i < Size; i++)
{
    //Create the game object
    Tiles[i] = GameObject.Instantiate (Resources.Load ("Tile")) as GameObject;  

    //Position it in the scene
    Tiles[i].transform.position = new Vector3(i * 0.32f, 0, 0);
}
If you assign the following script to the Start() function of a gameobject in your scene, you will see 10 Tile prefab objects appear when you Run your game.

Example 2: unity array c#

new List();

Example 3: array in c# unity

using UnityEngine;
using System.Collections;

public class Arrays : MonoBehaviour
{
    public GameObject[] players;

    void Start ()
    {
        players = GameObject.FindGameObjectsWithTag("Player");
        
        for(int i = 0; i < players.Length; i++)
        {
            Debug.Log("Player Number "+i+" is named "+players[i].name);
        }
    }
}