NullReferenceException: Object reference not set to an instance of an object

So unity is reporting an error that I don’t know how to fix.

The Error is:

NullReferenceException: Object reference not set to an instance of an object
VidaPlayer.OnTriggerStay2D (UnityEngine.Collider2D outro) (at Assets/Scripts/VidaPlayer.cs:33)

Here is the Player Life code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class VidaPlayer : MonoBehaviour
{
    public bool Vivo = true;
    public Image lifeBar;
    public int valorAtual = 10;
    //public int dano = 1;
    public float fireRate = 0.5f;
    private float nextAttack;

    private LocalDano inimigo;
    public GameObject LocalDano;
   
    void Start()
    {
        inimigo = LocalDano.GetComponent<LocalDano>();
    }

    void Update()
    {

    }
    void OnTriggerStay2D(Collider2D outro)
    {  
        if(outro.gameObject.CompareTag("DanoInimigo"))
        {  
            if(Time.time > nextAttack && valorAtual > 0)
            {  
                valorAtual -= inimigo.danoInimigo;
                lifeBar.fillAmount = (float)valorAtual / 10;
                nextAttack = Time.time + fireRate;
            }
            else if(valorAtual <= 0)
            {  
                Vivo = false;
                Destroy(gameObject);
            } 
        }
    }
}

Here is the Enemy Damage code.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LocalDano : MonoBehaviour
{
    //public Transform Inimigo;
    //public float vel = 100000.0f;

    public int danoInimigo = 1;
   
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        //transform.position = Vector2.MoveTowards(this.transform.position, Inimigo.transform.position, vel * Time.deltaTime);
    }
}

Thank you very much in advance

How to fix a NullReferenceException error

https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

Steps to success:

  • Identify what is null
  • Identify why it is null
  • Fix that
1 Like

LOL, Kurt beat me to it ;).

Anyway, the funny thing is that it stands right above your post. So Geovane a bit looking around and searching does not hurt.

1 Like

@MelvMay we desperately need a piece of Javascript in the NEW POST page that looks for “Null” and “Reference” and then instantly just abandons their message and sends them to the above link.

2 Likes

I know and agree and share the frustration but unfortunately there’s absolutely nothing I can do about it. I’m with you, just replying again and again unfortunately. If I had “the power” I’d see what I could do but I’ve suggested similar things myself and have asked other devs to post on the meta-forums etc.

As Master Yoda would say, “Hands Tied they are!”. :wink:

1 Like