c# coding question

Hi,

I am trying to get each gameobject that has the entity script on it, to register itself with the entity manager script only when it is enabled.

This is my singleton entity manager script:

using UnityEngine;
using System.Collections.Generic;

public class EntityManager : MonoBehaviour
{
    public static EntityManager instance { get; private set; }

    private static uint nextId = 0;
    public static uint NextId
    {
        get { return nextId++; }
    }

    private Dictionary<GameObject, Entity> entityLookup;

    private List<Entity> agents;
    public List<Entity> Agents
    {
        get { return agents; }
    }

    private void Awake()
    {
        instance = this;

        entityLookup = new Dictionary<GameObject, Entity>();
        agents = new List<Entity>();
    }

    public void RegisterEntity(Entity entity)
    {
        entityLookup.Add(entity.gameObject, entity);
        agents.Add(entity);
    }
}

And this is the entity script I put on each NPC:

using UnityEngine;
using PixelCrushers.LoveHate;

public class Entity : MonoBehaviour
{
    private uint id;
    public uint Id
    {
        get { return this.id; }
        set { this.id = value; }
    }

    public Vector3 Position
    {
        get { return this.transform.position; }
        set { this.transform.position = value; }
    }

    private FactionMember factionMember;

    public int FactionId
    {
        get { return this.factionMember.factionID; }
    }

    private void Awake()
    {
        factionMember = this.GetComponent<FactionMember>();
    }

    private void OnEnable()
    {
        this.Id = EntityManager.NextId;
        EntityManager.instance.RegisterEntity(this);
    }
}

When I hit play I keep getting the following error:

NullReferenceException: Object reference not set to an instance of an object
Entity.OnEnable () (at Assets/Stuff/Scripts/Components/Entity.cs:34)

Line 34 is:

EntityManager.instance.RegisterEntity(this);

*Edit, I have no clue what I am doing wrong.

It could be that the Entity script’s OnEnabled function is called before the EntityManager’s Awake function, which is when you assign instance as the EntityManager. This means before the Awake function is called, instance will be null. You could edit the instance property with a custom get, where if the reference is null use GameObject.FindObjectOfType<EntityManager>() to find the singleton.