Public referense and Show in editor

I have the following code. When I try to change the position I get an error that says “NullReferenceException: Object reference not set to an instance of an object”. I don’t understand why. My second question is why my grid list wont show up in my editors in unity. I have a picture of my editor.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class myGrid : MonoBehaviour
{
    private int width;
    private int height;
    private float size;

    public GameObject defualtSprite;

    [SerializeField]
    public GameObject [,] grid;

    private void Start()
    {
        myGrid grid = new myGrid(4, 2, 10);
    }

    public myGrid(int width, int height, float size)
    {
        this.width = width;
        this.height = height;
        this.size = size;

        grid = new GameObject[width, height];

        for(int x = 0; x < width; x++)
        {
            for (int y = 0; y < height; y++)
            {
                // My first method
                //Transform trans = defualtSprite.GetComponent<Transform>();
                //trans.position = new Vector3(x * size, y * size, 0);

                // My second method
                defualtSprite.transform.position = new Vector3(x * size, y * size, 0);

                grid[x, y] = defualtSprite;
            }
        }
    }
}

First place to check should be the docs: Unity - Manual: Script serialization

Unity can’t serialise collections beyond basic arrays and lists.

By default, Unity can’t show multi-dimensional arrays in the inspector.
Your other issue is exactly as it shows you in console, you can’t use new to create a MonoBehaviour. So, within Start, that doesn’t work. If you want to create it, you’d have to use AddComponent, however, if you did AddComponent in Start within the myGrid class, you’ll keep creating more and more myGrid components till it crashed/freezes Unity.

So if I can’t use new and AddComponent. What do you think I shuld do?

Replace public myGrid() with void CreateGrid(). You’re not using it as a constructor (you’re only setting up an array).
Then make sure that ‘defualtSprite’ is set in the Inspector.

Ah thank you, it works now :slight_smile:

Thanks for the dockument, I understand now :slight_smile: