Search Unity

I don't understand the mistake, I'm a newbie

Discussion in 'Scripting' started by Nixel2013, Sep 23, 2019.

  1. Nixel2013

    Nixel2013

    Joined:
    May 9, 2019
    Posts:
    143
    Error:
    NullReferenceException: Object reference not set to an instance of an object
    VidaExtra.SumaDeVida (UnityEngine.Collider player) (at Assets/Scripts/VidaExtra.cs:35)
    VidaExtra.OnTriggerEnter (UnityEngine.Collider other) (at Assets/Scripts/VidaExtra.cs:26)

    Code (CSharp):
    1. public class VidaExtra : MonoBehaviour
    2. {
    3.     public int CantidadDeVida;
    4.  
    5.     Health Vida;
    6.  
    7.  
    8.     private void Awake()
    9.     {
    10.  
    11.         Vida = GetComponent<Health>();
    12.  
    13.     }
    14.  
    15.     void OnTriggerEnter(Collider other)
    16.     {
    17.         if (other.CompareTag("Player"))
    18.         {
    19.             SumaDeVida(other);
    20.  
    21.         }
    22.  
    23.     }
    24.  
    25.  
    26.     void SumaDeVida(Collider player)
    27.     {
    28.         CantidadDeVida += Vida.currenthealth;
    29.  
    30.        // Destroy(gameObject);
    31.     }
    32. }
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    Did you attach a "Health" component to the same GameObject this script is running on?
     
  3. Nixel2013

    Nixel2013

    Joined:
    May 9, 2019
    Posts:
    143
  4. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    By dragging the "Health" script onto the object in the inspector, the same way you attach any script.
     
  5. Nixel2013

    Nixel2013

    Joined:
    May 9, 2019
    Posts:
    143
    necessary? because I'm calling him, I don't know if it's necessary to put it
     
  6. JeffDUnity3D

    JeffDUnity3D

    Joined:
    May 2, 2017
    Posts:
    14,446
    In Awake, check to make sure that Vida is not null.
     
    Joe-Censored likes this.
  7. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    21,192
    Completely necessary. GetComponent expects the component (in this case a script) to be attached to the Game Object that it's being called on. If a component isn't there it will return null and then when you go to use it you will get the error messages you're getting now.
     
    Joe-Censored and Nixel2013 like this.
  8. Nixel2013

    Nixel2013

    Joined:
    May 9, 2019
    Posts:
    143
    I already solved the problem, thank you all