Instantiate custom class returning null object

Viewed 73

Creating a Conway's Game of Life game and I am trying to fill the screen with an initial set of random Cells.

I created the "Cell" Class and within this I have a simple method that takes in a bool to set the Cell as alive or not.

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

public class Cell : MonoBehaviour
{
    public bool isAlive = false;
    public int numNeighbors = 0;

    public void SetAlive (bool alive)
    {
        isAlive = alive;

        if (alive)
        {
            GetComponent<SpriteRenderer>().enabled = true;
        } else 
        {
            GetComponent<SpriteRenderer>().enabled = false;
        }
    }
}

When Instantiating the GameObject (a 16x16 black square) as a Cell, I get a Null Object: print on console of the cell

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

public class Game : MonoBehaviour
{
    
    private static int SCREEN_WIDTH = 64;       // 1024 pixels
    private static int SCREEN_HEIGHT = 48;      // 768  pixels

    Cell[,] grid = new Cell[SCREEN_WIDTH, SCREEN_HEIGHT];   //grid for cells
    

    // Start is called before the first frame update
    void Start()
    {
        PlaceCells();
    }

    // Update is called once per frame
    void Update ()
    {
        
    }

    void PlaceCells ()
    {
        for (int y = 0; y < SCREEN_HEIGHT; y++)
        {
            for (int x = 0; x < SCREEN_WIDTH; x++)
            {   
                Cell cell = Instantiate(Resources.Load("Prefabs/Cell"), new Vector2(x, y), Quaternion.identity) as Cell;
                grid[x, y] = cell;
            }
        }

    }

    bool RandomAliveCell ()
    {
        int rand = UnityEngine.Random.Range (0, 100);

        if (rand > 75)
        {
            return true;
        }

        return false;
    }


}

I´m new to C# and to Unity so please, if you can, provide a more detailed explanation or documentation so I could learn more :)

Cell prefab Unity

0 Answers
Related