-1

Im making a game where you unlock doors with keys and its been working fine all day, however i have just opened Unity and in the console it says this:

NullReferenceException: Object reference not set to an instance of an object Door.OnTriggerStay2D (UnityEngine.Collider2D collision) (at Assets/Door.cs:25)

help?

Key.cs:

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

public class Key : MonoBehaviour{
    private SpringJoint2D spring;

    // Start is called before the first frame update
    void Start(){
        spring = GetComponent<SpringJoint2D>();
        GameObject backpack = GameObject.FindWithTag("Backpack");
        spring.connectedBody = backpack.GetComponent<Rigidbody2D>();
        spring.enabled = false;
    }
    private void OnTriggerEnter2D(Collider2D collision) {
        if(collision.gameObject.tag == "Player" && !spring.enabled){
            spring.enabled = true;
        }
    }

}

Door.cs:

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

public class Door : MonoBehaviour{
    public GameObject connectedDoor;
    public bool teleported = false;
    private GameObject player;

    // Start is called before the first frame update
    void Start(){
        player = GameObject.FindWithTag("Player");
    }

    // Update is called once per frame
    void Update(){
        if(teleported && Input.GetAxisRaw("Vertical") < 1){
            teleported = false;
        }
    }
    private void OnTriggerStay2D(Collider2D collision) {
        if(collision.gameObject.tag == "Key" && Input.GetAxisRaw("Vertical") == 1) {
            if(Input.GetAxisRaw("Vertical") == 1 && !teleported){
                player.transform.position = connectedDoor.transform.position;
                connectedDoor.GetComponent<Door>().teleported = true;
            }
        }
    }
}
  • 2
    Did you assign a `GameObject` to `connectedDoor` in the Unity editor? – Zserbinator Dec 18 '21 at 21:29
  • @Zserbinator Yes it was working fine earlier idk what happened – D4RKTORNADO Dec 18 '21 at 21:31
  • Maybe try adding a null check to line 23, because I think that could be its problem: `if(Input.GetAxisRaw("Vertical") == 1 && !teleported && connectedDoor != null){` – Zserbinator Dec 18 '21 at 21:36
  • @Zserbinator Hi, i added the same line as told and it hasnt changed, the message in the console is still the same, i dont know what the issue could be i am quite new to unity – D4RKTORNADO Dec 18 '21 at 21:44

1 Answers1

2

This line here is causing an error: connectedDoor.GetComponent<Door>().teleported = true; you might have set connectedDoor to something else somewhere else in your code.

There might be an object with the 'Key' component that hasn't got a connectedDoor that you haven't noticed, try check each object for a Key component

B33bo
  • 21
  • 6