unity-game-engineruntimenullreferenceexceptionassignunity-components

Accessing a runtime assigned Object from another component?


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;

Solution

  • 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);
    }