-4

I have a PlayerMovement class and an EnemyMovement class. My enemy moves only when the player moves.

When an enemy is created, it should get added to a list of enemies in the PlayerMovement object.

This is what I've got:

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

public class EnemyMovement : MonoBehaviour
{
    public PlayerMovement player;

    void Awake()
    {
      player.Subscribe(this);
    }

    public void Move()
    {
      print("Enemy moved!");
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
  public static ArrayList enemies;

  void Start()
    {
      enemies = new ArrayList();
    }

  void Message(Direction direction)
  {
    foreach(EnemyMovement enemy in enemies)
    {
      enemy.Move();
    }
  }

  public void Subscribe(EnemyMovement enemy)
  {
    enemies.Add(enemy);
  }
}

However, Unity gives me the error

NullReferenceException: Object reference not set to an instance of an object.

How do I correctly pass a self reference of one object to another?

user3574603
  • 3,364
  • 3
  • 24
  • 59

1 Answers1

1

Where I’m relying on myself, or another user, to enter references through the Inspector, I generally like to add checks to the code. For example:

public class EnemyMovement : MonoBehaviour
{
    public PlayerMovement player;

    void Awake()
    {
        if (player == null)
        {
            Debug.LogError ( “PlayerMovement is null.” );
            return;
        }
        player.Subscribe(this);
    }

    // ..
}

And then if I know I want an initialised item from the start, I will generally do so in the definition, like so:


public class PlayerMovement : MonoBehaviour
{
  public static ArrayList enemies = new();

  // ..
}

That way you stand a much smaller chance of getting a NullRegerence exception.

Milan Egon Votrubec
  • 3,696
  • 2
  • 10
  • 24