如何在我的代码中实现“ if(TargetToFind!= null)”,以解决“缺少参考异常:错误消息

时间:2019-06-15 08:59:56

标签: c# unity3d

所以我正在为学校制作这款游戏​​,但遇到了这个问题。我已经对其进行了研究,但找不到与我处境相同的人。

我对Unity和MonoDevelop的所有内容都是新手,所以我不知道该怎么做。在线上没有任何内容告诉我或指导我将新代码确切地放置在现有代码中的什么位置。

尽管我确定应该将其放置在负责相机运动的代码中。

关于玩家的摄像机运动:

public class MoveCamera : MonoBehaviour {
    public Transform target;

    public float smoothSpeed = 0.125f;
    public Vector3 offset;

    void FixedUpdate ()
    {
        Vector3 desiredPosition = target.position + offset;
        Vector3 smoothedPostion = Vector3.Lerp (transform.position, desiredPosition, smoothSpeed);
        transform.position = smoothedPostion;

        transform.LookAt(target);
    }
}

以及玩家/用户的动向:

private Rigidbody rb;

void Start () 
{
    rb = GetComponent<Rigidbody> ();
}

void FixedUpdate () {
    GetComponent<Rigidbody> ().velocity = new Vector3 (0, 0, 20);

    float moveHorizontal = Input.GetAxis ("Horizontal");

    Vector3 Movement = new Vector3 (moveHorizontal, 0.0f, 0.0f);

    rb.AddForce (Movement*Speed);
}

void OnCollisionEnter(Collision other)
{
    if (other.gameObject.tag == "Obstacle")
    {
       Destroy(gameObject);
    }
}

现在,由于我刚开始从事这个项目,所以它没有引起任何重大错误。但是,恐怕随着我在不解决此问题的情况下前进,将会破坏游戏。

出现的错误是“ MissingReferenceException:'Transform'类型的对象已被破坏,但您仍在尝试访问它。脚本应检查它是否为null或不应该破坏该对象。“ < / p>

1 个答案:

答案 0 :(得分:2)

在OnColission输入中,您可以销毁播放器。 但是相机正在尝试访问(target)。 正如在调试器中所说的,您有2个选项: 一是您不破坏GameObject, 否则当您被摧毁时便停止游戏。 如果目标仍然存在,您还可以检入fixedupdate:

if (!target)
{
    return;
}

希望我能对您有所帮助。