2

As it stands I can't seem to make sense of the events in my program. I have two components. One called EnemyMeleeSwitching and one called EnemyAI.

EnemyMeleeSwitching, who's script is contained in the same parent level as EnemyAI at runtime selects a random Weapon(object) from a list and assigns the enemyWeapon object variable as that Weapon.

Now I am under the impression that accessing the EnemyMeleeSwitching component and further the Weapon component from my EnemyAI script should allow me to then access enemyWeapon however I am getting a NullReferenceException.

Does this have something to do with execution order? Is my EnemyAI script trying to access enemyWeapon before it's been assigned?

EnemyMeleeSwitching Code below:

public class EnemyWeaponSwitching : MonoBehaviour 
{
    public Weapon enemyWeapon;
    public Weapon weapon01;
    public Weapon weapon02;

    private List<Weapon> weapons = new List<Weapon>();

    void Start()
    {
        weapons.Add(weapon01);
        weapons.Add(weapon02);

        enemyWeapon = weapons[Random.Range(0, weapons.Count)];

        foreach (Weapon weapon in weapons)
        {
            weapon.SetActive(false);
        }

        enemyWeapon.SetActive(true);
    }
}

EnemyAI Code call below:

weapon = (Weapon)gameObject.GetComponent<EnemyWeaponSwitching>().enemyWeapon;
user3071284
  • 6,955
  • 6
  • 43
  • 57
MattGarnett
  • 545
  • 3
  • 20

2 Answers2

1

Yes, it is possible that EnemyAI is accessing enemyWeapon before it is assigned. 1. Try to move your code from EnemyWeaponSwitching Start() method in Awake() method. Or 2. Try to change the execution order or your scripts.

Ilona Hari
  • 533
  • 3
  • 14
0

As a follow up to my question I managed to solve this problem by moving the code from Start() to a new function which I called after establishing a reference to EnemyWeaponSwitching. This assigned the required object variable before I then called it in my EnemyAI code.

New code below:

(EnemyAI)

weaponSwitching = gameObject.GetComponentInChildren<EnemyWeaponSwitching>();
        weaponSwitching.GenerateWeapon();

        attackRange = weaponSwitching.enemyWeapon.maxAttackRange;

(EnemyWeaponSwitching)

public void GenerateWeapon()
{
    weapons.Add(weapon01);
    weapons.Add(weapon02);

    enemyWeapon = weapons[Random.Range(0, weapons.Count)];

    foreach (Weapon weapon in weapons)
    {
        weapon.SetActive(false);
    }

    enemyWeapon.SetActive(true);
}
MattGarnett
  • 545
  • 3
  • 20