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

Hello, I can’t seem to fix this problem. If you know how I should fix it, I would be very happy. Here’s my 2 scripts:

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

public class ShootAwayBat : MonoBehaviour
{
    public Rigidbody2D rb;
    public float speed;
    public bool sak;
    public bool sak2;
    public GameObject enemy;
   
    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        if (sak == true)  {
            transform.position += transform.right * speed * Time.deltaTime;
        }
        if (Input.GetKeyDown(KeyCode.Q)) {
            Debug.Log("ENsak");
            sak = true;
        }
    }
    void OnTriggerEnter2D (Collider2D col) {
        if (col.gameObject.tag == "Head") {
            col.gameObject.GetComponent<teleport> ().Teleport1();
        }
    }
}

and the other:

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

public class teleport : MonoBehaviour
{
    public Transform player;
    public Transform ensak;
    // Start is called before the first frame update
    void Start()
    {
        ensak = GameObject.FindGameObjectWithTag("ensak").transform;
        player = GameObject.FindGameObjectWithTag("Player").transform;   
    }
    public void Teleport1() {
        ensak.position = player.position;
        player.position = this.transform.position;
        ensak.position = this.transform.position;
    }
}

thanks!

What line is the error on?

2 Likes

[quote=“Zalosath, post:2, topic: 804540, username:Zalosath”]
What line is the error on?
[/quote] on the col.gameObject.GetComponent<teleport> ().Teleport1(); thanks!

You most likely don’t have a “teleport” component on the object you collided with.

If you think you do, you may be running that code on something you don’t expect to be. Try adding this before that line to get more info:

Debug.Log($"Trigger collided with object {col.gameObject.name}, teleport component is {col.GetComponent<teleport>() != null}", col.gameObject);

If you click on this log message in the console when it says “False” on it, it will highlight the thing you collided with.

okay, but I have a script called teleport on the object I collided with…

oh, sry… I did not have a script called teleport, I had it on the parent… Thank you

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.