Forum begins after the advertisement:


[Part 10] Can’t add new weapon

Home Forums Video Game Tutorial Series Creating a Rogue-like Shoot-em Up in Unity [Part 10] Can’t add new weapon

Viewing 5 posts - 1 through 5 (of 5 total)
  • Author
    Posts
  • #13080
    Kai
    Participant

    I got this error when adding new weapon:

    NullReferenceException: Object reference not set to an instance of an object
    InventoryManager.AddWeapon (System.Int32 slotIndex, WeaponController weapon) (at Assets/Script/Player/InventoryManager.cs:51)
    PlayerStats.SpawnWeapon (UnityEngine.GameObject weapon) (at Assets/Script/Player/PlayerStats.cs:325)
    InventoryManager+<>c__DisplayClass18_0.<ApplyUpgradeOptions>b__0 () (at Assets/Script/Player/InventoryManager.cs:153)

    Level up weapon, adding new passive item and level up passive item work fine but i got that error choosing new weapon.
    The errors point at
    InventoryManager

    weaponLevels[slotIndex] = weapon.weaponData.Level;

    PlayerStat

    inventory.AddWeapon(weaponIndex, spawnedWeapon.GetComponent<WeaponController>()); // Add weapon to its inventory slot

    InventoryManager

    upgradeOption.upgradeButton.onClick.AddListener(() => player.SpawnWeapon(chosenWeaponUpgrade.initialWeapon)); //Apply the button functionality
    #13081
    Terence
    Keymaster

    Hi Kai, did you forget to add the Weapon Controller component to your prefab?

    #13082
    Terence
    Keymaster

    Just to add on, the issue should be in AddWeapon() because it is the first line in the stack track.

    The Null Reference exception means that one of the items in that line has a null variable that you are trying to access the property of. There are 3 variables there you try to access the property or method of, and one of them is null and is causing this issue:

    • inventory: If it is null, then inventory.AddWeapon() fails.
    • spawnedWeapon: If this is null, you will not be able to do GetComponent() with it.
    • GetComponent<WeaponController>(): Finally, if this is null, this may cause issues when inventory.AddWeapon() tries to use the variable.
    #13091
    Kai
    Participant

    I figured it out, I put the weapon prefab instead of weapon controller in the Initial Weapon field, I need to get my eyes checked lol, thanks for the help

    #13111
    Terence
    Keymaster

    No worries Kai, I’ve been coding for nearly a decade now and this kind of stuff still happens to me occasionally. Totally normal.

Viewing 5 posts - 1 through 5 (of 5 total)
  • You must be logged in to reply to this topic.

Go to Login Page →


Advertisement below: