I am creating a simple program in Unity C# that will generate a 2d grid using a 2d sprite prefab. I am stuck here, I don't know what to do. When ran, I receive an error.

Assets/Generator.cs(22,75): error CS0165: Use of unassigned local variable `grid_object'

I am a beginner, so I'm not sure what to do. This is most likely a rookie mistake, so thanks in advance.

using UnityEngine;
using System.Collections;
public class Generator : MonoBehaviour {

public float Width = 20;
public float Height = 20;
public Transform grid_object;
private GameObject [,] grid = new GameObject[20,20];

void Start () {

private void CreateGrid() {

    for (int x = 0; x < Width; x++) {
        for (int y = 0; y < Height; y++) {
            GameObject grid_object = (GameObject)Instantiate(grid_object);
            grid_object.transform.position = new Vector2(
            grid[x,y] = grid_object;
  • 1
    \$\begingroup\$ A core requirement, in programming, is that you give variables unique names. Your issue comes from having two variables labelled "grid_object". Hopefully, this answers your question; this is ultimately a generic programming question, as this is something that is not specific to game development. We don't consider these sort of questions on topic for GameDevSE, but feel free to look for more information at StackOverflow. \$\endgroup\$ – Gnemlock Dec 22 '16 at 5:37
  • \$\begingroup\$ This is example of 2d grid generation that will help you \$\endgroup\$ – Seyed Morteza Kamali Dec 22 '16 at 6:07

Your Transform grid_object and your GameObject grid_object have the same name. Change one of them to something different and it should work.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.