• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by MBezerra · Mar 23, 2020 at 03:30 AM · nullreferenceexception

NullReferenceException Please Help

I've found a good number of questions similar to mine, and even after reviewing those answers, my problem persists. All I'm trying to create is a method for the player to pick up and store weapons to use within their inventory, and aside from that, everything else works as intended, but as soon as the player character tries to pick up a weapon, the game window pauses and gives this error.

Here's the PlayerController script for reference

 public class PlayerController : MonoBehaviour
 {
     public GameObject Player;
     public Inventory Weapons;
     public WeaponFamily pickup;
 
     public float turnSpeed = 20f;
     public float vel = 20f;
 
     Rigidbody m_Rigidbody;
     Vector3 m_Movement;
     Quaternion m_Rotation = Quaternion.identity;
 
     public Transform Right, Left;
 
     // Start is called before the first frame update
     void Start()
     {
          m_Rigidbody = GetComponent<Rigidbody>();
          Weapons = new Inventory();
    }
 
     // Update is called once per frame
     void FixedUpdate()
     {
         float horizontal = Input.GetAxis("Horizontal");
         float vertical = Input.GetAxis("Vertical");
 
         m_Movement.Set(horizontal, 0f, vertical);
         m_Movement.Normalize();
 
         m_Rigidbody.MovePosition(m_Rigidbody.position + ((m_Movement * vel)/10));
         m_Rigidbody.MoveRotation(m_Rotation);
 
         Vector3 desiredForward = Vector3.RotateTowards(transform.forward, m_Movement, turnSpeed * Time.deltaTime, 0f);
         m_Rotation = Quaternion.LookRotation(desiredForward);
     }
 
     void Update()
     {
         if (Input.GetKeyDown(KeyCode.Alpha1))
         {
             Weapons.SelectWeapon(0);
         }
 
         if (Input.GetKeyDown(KeyCode.Alpha2))
         {
             Weapons.SelectWeapon(1);
         }
 
         if (Input.GetKeyDown(KeyCode.Alpha3))
         {
             Weapons.SelectWeapon(2);
         }
 
         if (Input.GetKeyDown("space"))
         {
             Shoot(Weapons.CurrentWeapon);
         }
     }
 
     void Shoot(WeaponFamily CurrentWeapon)
     {
 
     }
 
     private void OnTriggerEnter(Collider other)
     {
         pickup = other.gameObject.GetComponent<WeaponFamily>();
         if(other.CompareTag("Weapon"))
         {
             Weapons.PickupWeapon(pickup);
         }
     }
 }

The last line method: the OnTriggerEnter is the area where the error lies. I'm effectively just trying to tell the game to recognize if the player comes in contact with a weapon, it performs that method PickupWeapon, which loads it into the player's Inventory

Class for reference

 public class Inventory : MonoBehaviour
 {
     public PlayerController Player;
 
     public List<WeaponFamily> Weapons;
     public WeaponFamily CurrentWeapon;
     public int maxWeapons = 3;
 
     // Start is called before the first frame update
     void Start()
     {
         Weapons = new List<WeaponFamily>();
     }
 

     // Update is called once per frame
     void Update()
     {
         
     }
 
     public void PickupWeapon(WeaponFamily w)
     {
         bool inInventory = false;
 
         for(int i =0; i < Weapons.Count; i++)
         {
             if(w == Weapons[i])
             {
                 inInventory = true;
             }
         }
         if (Weapons.Count < maxWeapons && !inInventory)
         {
                 Weapons.Add(w);
 
                 w.gameObject.SetActive(false);
                 w.GetComponent<Collider>().isTrigger = false;
 
                 w.transform.parent = Player.transform;
                 w.transform.position = Vector3.zero;
                 w.transform.rotation = Player.transform.rotation;
         }
     }
 
     public void SelectWeapon(int index)
     {
         if (Weapons.Count > index && Weapons[index] != null)
         {
             CurrentWeapon = Weapons[index];
         }
         CurrentWeapon.gameObject.SetActive(true);
     }
 }


Thanks in advance for the tips.

Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image CobbledGames · Mar 23, 2020 at 05:33 PM 0
Share

I'm not answering this specifically but this link I will provide will be useful on knowing what a NullReferenceException is and how to deal with them: https://docs.unity3d.com/$$anonymous$$anual/NullReferenceException.html

1 Reply

· Add your reply
  • Sort: 
avatar image
1

Answer by Namey5 · Mar 23, 2020 at 07:29 AM

At line 20, you create a new instance of the Weapons variable as type Inventory. This would normally be fine, however the Inventory class inherits from Unity's MonoBehaviour class. Because MonoBehaviours are supposed to be exclusively components attached to GameObjects, you cannot manually create an instance of a MonoBehaviour. Instead, the instance has to exist somewhere in the scene, be it on the player object or somewhere else. This is why you are getting a null reference exception - even though you attempt to create a new Inventory, it doesn't happen by design, and thus when you try to add a weapon to it, you end up accessing an object that doesn't exist. If you wish for Inventory to be a regular class and not directly attach it to an object in the scene, then you can change it like so;

  public class Inventory
  {
      public PlayerController Player;
  
      public List<WeaponFamily> Weapons;
      public WeaponFamily CurrentWeapon;
      public int maxWeapons = 3;
  
      public Inventory ()
      {
          Weapons = new List<WeaponFamily>();
      }
  
      public void PickupWeapon(WeaponFamily w)
      {
          ...
      }
  
      public void SelectWeapon(int index)
      {
          ...
      }
  }

Because Inventory is no longer a MonoBehaviour, functions like Start and Update no longer exist. However, you can now call the object's constructor (like you do when you create the Weapons variable), and as such you can move your initialisation code from Start into the constructor.

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image MBezerra · Mar 23, 2020 at 02:56 PM 0
Share

What you say makes sense, and I appreciate your help, but that didn't seem to solve the problem, the same line's producing the same error whenever I try to pick up any weapon. It's the line that class the PickupWeapon function within the PlayerController script.

avatar image Namey5 MBezerra · Mar 23, 2020 at 11:33 PM 0
Share

From the looks of it, 'Player' would still be unassigned, which would also give a NullReferenceException at line 40 in your original inventory script. You would need to pass it in via the constructor;

 public Inventory (PlayerController player)
 {
     Weapons = new List<WeaponFamily>();
     Player = player;
 }

Then, when you create a new inventory;

 Weapons = new Inventory (this);

The way to look for NRE's is to find the line at which the exception is occurring and make sure that all objects involved are fully created.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

127 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Allocating Game Object name dynamically using Find 0 Answers

Why am I getting a NullReferenceException while trying to set a gameobjects animation frame? 0 Answers

NullReferenceException .. problem with Camera.main.transform 2 Answers

Raycasting null object reference error 1 Answer

Editing in Animator removes Player tag 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges