未设置为对象统一实例的对象引用
本文关键字:实例 对象引用 设置 对象 | 更新日期: 2023-09-27 17:55:06
这是我的玩家刷出代码,但我得到一个空引用异常错误。
public class PlayerSpawn : MonoBehaviour
{
public Transform playerSpawn;
public Vector2 currentTrackPosition;
public bool activeRespawnTimer = false;
public float respawnTimer = 1.0f;
public float resetRespawnTimer = 1.0f;
void Start ()
{
if(playerSpawn != null)
{
transform.position = playerSpawn.position;
Debug.Log(playerSpawn);
}
}
void Update ()
{
if(activeRespawnTimer)
{
respawnTimer -= Time.deltaTime;
}
if(respawnTimer <= 0.0f)
{
transform.position = currentTrackPosition;
respawnTimer = resetRespawnTimer;
activeRespawnTimer = false;
}
}
void OnTriggerEnter2D(Collider2D other)
{
//im getting the error messege at this position
if(other.tag == "DeadZone")
{
activeRespawnTimer = true;
}
if(other.tag == "CheckPoint")
{
currentTrackPosition = transform.position;
}
}
}
有什么问题吗?谢谢你的帮助。
给定您提到的空引用异常发生的位置,看起来好像other
或other.tag
是空的。考虑到OnTriggerEnter
只在实际对象进入触发器时被调用,我高度怀疑other
是空的,除非它在调用方法之前被销毁。无论如何,安全总比后悔好。
一个简单的解决方案是:
void OnTriggerEnter2D(Collider2D other)
{
if(other != null && other.tag != null)
{
if(other.tag == "DeadZone")
{
activeRespawnTimer = true;
}
if(other.tag == "CheckPoint")
{
currentTrackPosition = transform.position;
}
}
}
如果这仍然抛出异常,那么一定是其他原因导致了问题,所以让我知道这是如何解决的。