How to create public non-static objects within public non-static objects?

I’m trying to make a grid of small games of snake to train a neural network and within each individual game board I want to instantiate a snake, a food, and a neural net object.
for each of those objects I have something like this:

public Snake _snake;
public Snake snake;

public void Init ()
{
    snake = Instantiate(_snake);
}

but the problem is that unity expects an object reference for both _snake and snake before runtime but I need the snake to be public and non-static.
Is there something I’m missing?

Unity do not need a reference for any variable until you read it. Will give you an error when executing Instantiate(_snake) if _snake is still null, but not before

This seems a little confused. What you are doing is trying to use _snake before you are instantiating it.

Instantiate needs a reference to an Object (prefab) in order to instantiate a copy of it. You cant instantiate null which is what _snake will be unless its a class.

You could do a null check if you need to do it at run time. or you could just make sure _snake is initialised before you call Init();


That said I am not entirely sure why you would even need to write it like this, surely you would just have a component that does your game setup and it would be more like:

public GameObject Prefab; // Set this in the editor before running the game.
public int Amount = 12;
public List<Object> Snakes = new List<Object>(); // Can cast this to the component type if necessary
    
public void InitSnakes() 
{
    if(Prefab == null) return; // Probably best to throw an exception here anyway.
    for(int i = 0; i < Amount; i++) 
    {
        Snakes.Add(Instantiate(Prefab));
    }
}