【问题标题】:OnTriggerStay2D Null Reference Exception [duplicate]OnTriggerStay2D 空引用异常 [重复]
【发布时间】: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 &amp;&amp; !teleported &amp;&amp; connectedDoor != null){
  • @Zserbinator 嗨,我添加了与告知相同的行并且它没有改变,控制台中的消息仍然相同,我不知道问题可能是我对统一很陌生跨度>

标签: c# unity3d


【解决方案1】:

此行导致错误: connectedDoor.GetComponent&lt;Door&gt;().teleported = true; 您可能已将 connectedDoor 设置为代码中的其他位置。

可能有一个带有“Key”组件的对象没有您没有注意到的 connectedDoor,请尝试检查每个对象是否有 Key 组件

【讨论】:

  • 谢谢你是对的!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-02
  • 1970-01-01
相关资源
最近更新 更多