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
Answer by NoseKills · Dec 09, 2015 at 04:47 PM
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 ;-)
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.
I did search, however I was not sure what to look for. I did not know I had to cast my array objects back to GameObjects. Thanks for the help.
Your answer
Follow this Question
Related Questions
Creating a grid that holds objects of different sizes? 0 Answers
array of raycasts in grid based game 0 Answers
assigning several positions and call array of raycasts 0 Answers
Cell size to Canvas size 1 Answer
coordinate transformation 0 Answers