【发布时间】:2022-01-21 04:58:58
【问题描述】:
我正在制作一个游戏,您可以用钥匙解锁门,并且它整天都运行良好,但是我刚刚打开 Unity,在控制台中显示:
NullReferenceException:对象引用未设置为对象的实例 Door.OnTriggerStay2D(UnityEngine.Collider2D 碰撞)(在 Assets/Door.cs:25)
帮助?
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;
}
}
}
}
【问题讨论】:
-
您是否在 Unity 编辑器中为
connectedDoor分配了GameObject? -
@Zserbinator 是的,之前它工作正常,知道发生了什么
-
也许尝试在第 23 行添加一个空检查,因为我认为这可能是它的问题:
if(Input.GetAxisRaw("Vertical") == 1 && !teleported && connectedDoor != null){ -
@Zserbinator 嗨,我添加了与告知相同的行并且它没有改变,控制台中的消息仍然相同,我不知道问题可能是我对统一很陌生跨度>