关于错误“对象引用未设置为对象实例”的问题

时间:2018-10-25 12:14:38

标签: c# unity3d

我正在尝试制作FPS控制器脚本,以便可以在Unity中与角色一起行走,跳跃和飞行。 I followed this tutorial right here.

我遇到的问题是,每当我尝试在Unity中运行脚本时,都会出现以下错误:

NullReferenceException: Object reference not set to an instance of an object
PlayerController.Update () (at Assets/PlayerController.cs:65)

我确实了解该错误的含义,但我只是不了解该错误的产生原因和解决方法。我希望你们能在这里帮助我。我一直在寻找一个好的剧本来使我的角色飞起来(也许我看起来还不够好)。

可以在这里查看代码:

播放器控制器脚本:

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

public class PlayerController : MonoBehaviour {

Rigidbody rb;

public bool isFlying, isGrounded;
public float w_speed, r_speed, fly_speed, fly_boost, mouse_sensitivity, Jump_Height, Float_Force;
private float g_speed, f_speed, mouseX, mouseY;

// Use this for initialization
void Start () {

    rb = GetComponent<Rigidbody>();

    isFlying = false;
    isGrounded = true;
}

// Update is called once per frame
void Update () {
    //Base Settings
    var gx = Input.GetAxis("Horizontal") * g_speed;
    var fx = Input.GetAxis("Horizontal") * f_speed;
    var gz = Input.GetAxis("Vertical") * g_speed;
    var fz = Input.GetAxis("Vertical") * f_speed;

    mouseX -= Input.GetAxis("Mouse Y") * mouse_sensitivity;
    mouseY += Input.GetAxis("Mouse X") * mouse_sensitivity;

    if (Input.GetKey(KeyCode.LeftShift))
    {
        g_speed = r_speed;
        f_speed = fly_boost;
    }
    else
    {
        g_speed = w_speed;
        f_speed = fly_speed;
    }

    if (isFlying)
    {
        rb.drag = 1;
        mouseX = Mathf.Clamp(mouseX, -90, 90);

        transform.Translate(fx, 0, fz);

        if (Input.GetKey(KeyCode.Space))
        {
            rb.AddForce(transform.up * Float_Force, ForceMode.Force);
        }
    }
    else
    {
        rb.drag = 0;
        mouseX = Mathf.Clamp(mouseX, -60, 60);

        transform.Translate(gx, 0, gz);
    }

    transform.rotation = Quaternion.Euler(0, mouseY, 0);
    Camera.main.transform.rotation = Quaternion.Euler(mouseX, mouseY, 0);

    if(Input.GetKeyUp(KeyCode.Space) && isGrounded)
    {
        isGrounded = false;
        rb.AddForce(transform.up * Jump_Height, ForceMode.Impulse);
    }

    if(Input.GetKeyDown(KeyCode.Space) && !isGrounded)
    {
        isFlying = true;
    }

}

private void OnCollisionEnter(Collision collision)
{
    isGrounded = true;
    isFlying = false;
}
}

本教程中显示的世界物理脚本:

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

public class WorldPhysics : MonoBehaviour {

    public float Gravity_Strength;

    // Update is called once per frame
    void Update () {
        Physics.gravity = new Vector3(0, -Gravity_Strength, 0);
    }
}

0 个答案:

没有答案
相关问题