jayj593
jayj593

Reputation: 68

How to properly add an object to a list when the list is a custom class object?

I get a null reference exception when I try to add a region to the list and have no idea what I'm doing wrong. I simply can't figure it and I've done this a million times.

public List<Region> regions;

public class Region
{
    public int x_size;
    public int y_size;

    public enum terrain
    {
        desert,
        lowlands,
        crater,
        city
    };

    public terrain ground;
}

private void NewRegion()
{
    Region thisRegion = new Region();
    thisRegion.x_size = Random.Range(25, 50);
    thisRegion.y_size = Random.Range(25, 50);
    thisRegion.ground = Region.terrain.desert;
    regions.Add(thisRegion);
}

Upvotes: 0

Views: 40

Answers (3)

derHugo
derHugo

Reputation: 90872

You should make Region a [Serilizable] type:

[Serializable]
public class Region
{
    public int x_size;
    public int y_size;

    public enum terrain
    {
        desert,
        lowlands,
        crater,
        city
    };

    public terrain ground;
}

Since the field regions is public it would be automatically serilaized and initialized by the Unity Inspector anyway if the Region was serializable.

So now the upper code would have two advantages

  • You don't have to have the code

    region = new List<Region>();
    

    nowhere. It would be initaialized automatically by Unity.

    It is still recommneded to have it, though, but I wouldn't do it in Start but simply like

    public List<Region> regions = new List<Region>();
    
  • The other really huge advantage is that now you should actually see that list in the Unity Inspector so you can directly from the Editor add and adjust elements without having to hardcode them via a script.

Upvotes: 0

KYL3R
KYL3R

Reputation: 4073

The regions list is null, you can't add anything to it. In Start() do:

regions = new List<Region> ();

Upvotes: 1

Skrface
Skrface

Reputation: 1420

You just did not instanciate your list of Region (regions), so it is null. Look at the new List<Region>() part :

public List<Region> regions = new List<Region>();

public class Region
{
    public int x_size;
    public int y_size;

    public enum terrain
    {
        desert,
        lowlands,
        crater,
        city
    };

    public terrain ground;
}

private void NewRegion()
{
    Region thisRegion = new Region();
    thisRegion.x_size = Random.Range(25, 50);
    thisRegion.y_size = Random.Range(25, 50);
    thisRegion.ground = Region.terrain.desert;
    regions.Add(thisRegion);
}

Upvotes: 2

Related Questions