[SOLVED]NullReferenceException: Object reference not set to an instance of an object

Hello everyone,

As I am fairly new to unity I have encountered a problem, which persists for a while now and even if I have searched online for a solution, still couldn’t find one. In both the scripts I have uploaded, I get the same error
NullReferenceException: Object reference not set to an instance of an object in line 21 and still can’t understand why. Any help is appreciated.

using UnityEngine;
using System.Collections;

public class EnemyHealthController : MonoBehaviour {

    public float enemyHealth;
    // Use this for initialization

    public void Damage(float DamageCount)
    {
        enemyHealth -= DamageCount;
        if(enemyHealth<=0)
        {
            Destroy(gameObject);
        }
    }

    void OnTriggerEnter2D(Collider2D otherCollider)
    {
        PlayerShotsController Shot = otherCollider.gameObject.GetComponent<PlayerShotsController>();
        Damage(Shot.damage);
    }

    void OnCollisionEnter2D(Collision2D collision)
    {
        string tag = collision.gameObject.tag;
        if(tag == "Player")
        {
            Destroy(gameObject);
        }
    }

    void Start () {
   
    }
   
    // Update is called once per frame
    void Update ()
    {

    }
}
using UnityEngine;
using System.Collections;

public class PlayerHealthController : MonoBehaviour {

    public float playerHealth;
    // Use this for initialization

    public void Damage(float DamageCount)
    {
        playerHealth -= DamageCount;
        if (playerHealth <= 0)
        {
            Destroy(gameObject);
        }
    }

    void OnTriggerEnter2D(Collider2D otherCollider)
    {
        EnemyShotsController Shot = otherCollider.gameObject.GetComponent<EnemyShotsController>();
        Damage(Shot.damage);
    }

    void OnCollisionEnter2D(Collision2D collision)
    {
        EnemyController enemy = collision.gameObject.GetComponent<EnemyController>();
        Damage(enemy.collisionDamage);
    }
   
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }
}
1 Like

OnTriggerEnter will fire when “any” object that can collide with the layer intersects your layer. say for example your trigger on the “Player” touches the ground on the “environment” layer. OnTriggerEnter will fire if those two layers are configured to be colliable to each other.

that said not every collider that triggers the function will have a “PlayerShotController” or “EnemyShotController” thus in those cases GetComponent will return null because it didn’t find any component attached to the collider.

so your OnTriggerEnter (and OnCollistionEnter) functions need to check if the Shot or enemy is null before applying any damage.

void OnTriggerEnter2D(Collider2D otherCollider)
{
    EnemyShotsController Shot = otherCollider.GetComponent<EnemyShotsController>();

    if(Shot != null)
        Damage(Shot.damage);
}
7 Likes

That solved it for me. You are the man, thanks a lot!

2 Likes

I have this error and cant find the solution.

NullReferenceException: Object reference not set to an instance of an object
RubyController.ChangeHealth (System.Int32 amount) (at Assets/Scripts/RubyController.cs:75)
EnemyController.OnCollisionEnter2D (UnityEngine.Collision2D other) (at Assets/Scripts/EnemyController.cs:66)

The script :
Ruby Controller:

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

public class RubyController : MonoBehaviour
{
  public float speed = 3.0f;
  public int maxHealth = 5;
  public int health { get { return currentHealth; }}
  int currentHealth;
  public float timeInvincible = 2.0f;
  bool isInvincible;
  float invincibleTimer;

 
  Rigidbody2D rigidbody2d;
  Animator animator;
  public GameObject projectilePrefab;
  Vector2 lookDirection = new Vector2(1,0);

    // Start is called before the first frame update
    void Start()
    {
        rigidbody2d = GetComponent<Rigidbody2D>();
        currentHealth = maxHealth;
        animator = GetComponent<Animator>();
    }
  
    // Update is called once per frame
    void Update()
    {
        float horizontal = Input.GetAxis("Horizontal");
        float vertical = Input.GetAxis("Vertical");
               
        Vector2 move = new Vector2(horizontal, vertical);
       
      if(!Mathf.Approximately(move.x, 0.0f) || !Mathf.Approximately(move.y, 0.0f))
        {
          lookDirection.Set(move.x, move.y);
          lookDirection.Normalize();
        }
       
          animator.SetFloat("Look X", lookDirection.x);
          animator.SetFloat("Look Y", lookDirection.y);
          animator.SetFloat("Speed", move.magnitude);
       
          Vector2 position = rigidbody2d.position;
       
          position = position + move * speed * Time.deltaTime;
       
          rigidbody2d.MovePosition(position);
          if(Input.GetKeyDown(KeyCode.C))
            {
              Launch();
            }

      if (isInvincible)
        {
            invincibleTimer -= Time.deltaTime;
            if (invincibleTimer < 0)
                isInvincible = false;
        }
    }
      public void ChangeHealth(int amount)
    {
       if (amount < 0)
        {
            if (isInvincible)
                return;
           
            isInvincible = true;
            invincibleTimer = timeInvincible;
        }
        currentHealth = Mathf.Clamp(currentHealth +  amount, 0, maxHealth);
        UIHealthBar.instance.SetValue(currentHealth / (float)maxHealth);
        //Debug.Log(currentHealth + "/" + maxHealth);
    }
     void Launch()
   {
    GameObject projectileObject = Instantiate(projectilePrefab, rigidbody2d.position + Vector2.up * 0.5f, Quaternion.identity);
    Projectile projectile = projectileObject.GetComponent<Projectile>();
    projectile.Launch(lookDirection, 300);
    animator.SetTrigger("Launch");
   }

}

Enemy Controller:

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

public class EnemyController : MonoBehaviour
{
    public float speed = 3.0f;
    public bool vertical;
    public float changeTime = 3.0f;
    bool broken = true;

    public ParticleSystem smokeEffect;

    Rigidbody2D rigidbody2D;
    float timer;
    int direction = 1;
    Animator animator;
    // Start is called before the first frame update
    void Start()
    {
        rigidbody2D = GetComponent<Rigidbody2D>();
        timer = changeTime;
        animator = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        if(!broken)
        {
          return;
        }
        timer -= Time.deltaTime;

        if (timer < 0)
        {
            direction = -direction;
            timer = changeTime;
        }
       
       
        Vector2 position = rigidbody2D.position;

        if (vertical)
        {
            position.y = position.y + Time.deltaTime * speed * direction;
            animator.SetFloat("Move X", 0);
            animator.SetFloat("Move Y", direction);
        }
        else
        {
            position.x = position.x + Time.deltaTime * speed * direction;
            animator.SetFloat("Move X", direction);
            animator.SetFloat("Move Y", 0);
        }
        rigidbody2D.MovePosition(position);
    }
   
    void OnCollisionEnter2D(Collision2D other)
    {
        RubyController player = other.gameObject.GetComponent<RubyController >();

        if (player != null)
        {
            player.ChangeHealth(-1);
        }
    }
    public void Fix()
    {
     broken = false;
     rigidbody2D.simulated = false;
     animator.SetTrigger("Fixed");
     smokeEffect.Stop();
    }
}

Thank you!

I think you should make your own question so that someone will help u

I have this message:

NullReferenceException: Object reference not set to an instance of an object
MusicSystem.OnTriggerEnter (UnityEngine.Collider other) (at Assets/MyScripts/MusicSystem.cs:36)

And I have this in my inspector, I can’t see what I’m missing but I may be screen blind.

Guys could you pls help me why i get this error in this code? If you could i would really appreciate as a beginner.


6696391--768355--Screenshot 2021-01-06 at 22.21.35.png

Please don’t reply to a five year old thread. Start your own… it’s free.

How to report your problem productively in the Unity3D forums:

http://plbm.com/?p=220

If you have a nullref, the answer is always the same… ALWAYS. It is the single most common error ever. Don’t waste your life on this problem. Instead, learn how to fix it fast… it’s EASY!!

Some notes on how to fix a NullReferenceException error in Unity3D

  • also known as: Unassigned Reference Exception
  • also known as: Missing Reference Exception

http://plbm.com/?p=221

The basic steps outlined above are:

  • Identify what is null
  • Identify why it is null
  • Fix that.

Expect to see this error a LOT. It’s easily the most common thing to do when working. Learn how to fix it rapidly. It’s easy. See the above link for more tips.

This is the kind of mindset and thinking process you need to bring to this problem:

https://forum.unity.com/threads/why-do-my-music-ignore-the-sliders.993849/#post-6453695

Step by step, break it down, find the problem.

2 Likes

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

public class collect : MonoBehaviour
{
public push movement;
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == “collect”)
{
Destroy(other.gameObject);
}
}
private void OnCollisionEnter(Collision other)
{
if(other.gameObject.tag == “obs”)
{
movement.enabled = false;
}
}
}
mine code

Please stop posting to old threads. Go fix your error. Here’s how:

How to fix a NullReferenceException error

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

Three steps to success:

  • Identify what is null ← any other action taken before this step is WASTED TIME
  • Identify why it is null
  • Fix that