Creating a Grid using an Array with C#

Hi, I’m trying to create a grid with identical prefabs (which hoevwer need to have some sort of coordinate system). I’ve looked at examples and came up with the following (using raycast to detect the objects in the grid):

using UnityEngine;
using System.Collections;

public class GridGenerator : MonoBehaviour {

	public GameObject gridSpace;
	GameObject[,] boardArray = new GameObject[10,10];


	void Start () {

		GenerateGrid ();
	}

	void Update () {

		Ray detectobject = Camera.main.ScreenPointToRay (Input.mousePosition);
		RaycastHit hit;
		if (Physics.Raycast (detectobject, out hit, 100)) 
		{
			Debug.DrawLine (detectobject.origin, hit.point);

		}

	}

	void GenerateGrid()

	{

		for (int i = 0; i < boardArray.GetLength(0); i++) 
		{
			for (int j = 0; j < boardArray.GetLength (1); j++) 
			{

				boardArray[i,j] = Instantiate(gridSpace, new Vector3(j * 2,0,i * 2), Quaternion.identity);

			}
		}
	}
}

I get the error: “error CS0266: Cannot implicitly convert type UnityEngine.Object' to UnityEngine.GameObject’. An explicit conversion exists (are you missing a cast?)” I’m not sure what is meant by this.

Regards, Rob

I wonder if you tried to search for an answer before asking, since I get a full page of exactly the same answer to this exact problem when i Google the error you mention. It’s better than waiting 17 hours for a new answer :wink:

Instantiate() can be used to create many kinds of Objects, not just GameObjects like the Unity manual examples show.

In this non-generic version of the Instantiate() method, the compiler can’t know which kind of objects you are instantiating, so you have to tell it to the compiler explicitly by casting whatever Instantiate produces into a GameObject.

boardArray[i,j] = Instantiate(gridSpace, new Vector3(j * 2, 0, i * 2), Quaternion.identity) as GameObject

i.e. you are trying to put an Object into an array of GameObjects, which can’t be allowed since not all Objects are GameObjects.