Null Check

I’m probably jumping the gun here, and this question will be answered very soon. I thought I’d do this as a simple self-challenge.

At the moment if we press the 4 or 5 key we get a Null Reference error.

Is this a reasonable way to do the null reference check, and should be done here in the ActiveInventory.cs script? Thoughts?

    private void ChangeActiveWeapon()
    {
        if(ActiveWeapon.Instance.CurrentActiveWeapon != null)
        {
            Destroy(ActiveWeapon.Instance.CurrentActiveWeapon.gameObject);
        }

        if (!transform.GetChild(_activeSlotIndexNum).GetComponentInChildren<InventorySlot>())
        {
            ActiveWeapon.Instance.WeaponNull();
            return;
        }

        //Null question
        GameObject weaponToSpawn = transform?.GetChild(_activeSlotIndexNum)?.GetComponentInChildren<InventorySlot>()?.GetWeaponInfo()?.weaponPrefab;
        //Exit Change Active Weapon if no prefab was found. Stays on the previous Weapon
        if(weaponToSpawn == null) { return; }

        GameObject newWeapon = Instantiate(weaponToSpawn, ActiveWeapon.Instance.transform.position, Quaternion.identity);

        ActiveWeapon.Instance.transform.rotation = Quaternion.Euler(0f, 0f, 0f);

        newWeapon.transform.parent = ActiveWeapon.Instance.transform;

        ActiveWeapon.Instance.NewWeapon(newWeapon.GetComponent<MonoBehaviour>());
    }
1 Like

You’re right we’ll tackle it soon! I believe this specifically in the clean-up lecture at the end of the section if I recall. But later on, you’ll see I’ve tackled it in more or less the same way.

Great. Thanks Stephen

While this is usually fine, Unity does not want us to use the null-conditional operator here, so it’s probably best to do it the old way.

From the documentation for Unity’s Object (which transform inherits from):

It may work in some cases, but there is no guarantee that it will always be the case, so be aware of that

1 Like

I also solved this right away … like this:

        void ChangeActiveWeapon()
        {
          //...
           GameObject weaponToSpawn = invSlot.GetWeaponInfo()?.weaponPrefab;

            if (null != weaponToSpawn)
            {
              //...
            }
        }
1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms