Search Unity

Cant Link Ammunition And Text

Discussion in 'Editor & General Support' started by Mr_AgentFox, Jul 31, 2019.

  1. Mr_AgentFox

    Mr_AgentFox

    Joined:
    Jun 23, 2019
    Posts:
    59
    Does anyone know how to fix my issue? I have text that will not update with my ammo. It gives me this error in the console: "NullReferenceExeption: Object reference not set to an instance of an object" (I took out the important parts in the script down below.)

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections.Generic;
    3. using System.Collections;
    4. using UnityEngine.UI;
    5.  
    6. public class GunScript : MonoBehaviour
    7. {
    8.     public int maxAmmo = 100;
    9.     private int currentAmmo;
    10.  
    11.  
    12.     Text ammoTxt;
    13.  
    14.     void Awake()
    15.     {
    16.         ammoTxt = GetComponent<Text>();
    17.     }
    18.  
    19.     void Start()
    20.     {
    21.         maxAmmo = 100;
    22.         currentAmmo = maxAmmo;
    23.     }
    24.  
    25.     void Update()
    26.     {
    27.         ammoTxt.text = gameObject.GetComponent<GunScript>().currentAmmo.ToString();
    28.     }
    29.  
    30.     public void Shoot()
    31.     {
    32.         currentAmmo--;
    33.     }
    34. }
    35.  
    36.  
     
  2. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    It would be helpful if you mentioned which line the error occurs, but it is a good idea to check if GetComponent or similar methods are returning null before trying to use their returned reference. Especially when debugging this kind of issue.

    Do stuff like this:
    Code (csharp):
    1.     void Awake()
    2.     {
    3.         ammoTxt = GetComponent<Text>();
    4.         if (ammoTxt == null)
    5.         {
    6.             Debug.Log("ammoTxt is null in Awake() GunScript.cs");
    7.         }
    8.     }
    Also, what are you doing in Update? It makes no sense. You're effectively using GetComponent to get a reference to itself just to access a private variable.

    This:
    Code (csharp):
    1.     void Update()
    2.     {
    3.         ammoTxt.text = gameObject.GetComponent<GunScript>().currentAmmo.ToString();
    4.     }
    and this:
    Code (csharp):
    1.     void Update()
    2.     {
    3.         ammoTxt.text = currentAmmo.ToString();
    4.     }
    do the same thing.