一宿没睡。报错,不理解 VS没报错,unity却报错了 NullReferenceException: Object reference not set to an instance of an object
PlayerMovment.Start () (at Assets/Scipts/PlayerMovment.cs:39)
源码;
public class PlayerMovment : MonoBehaviour
{
private CharacterController characterController;
public float walkSpeed = 10f;//行走速度
public float runSpeed = 15f;//奔跑速度
public float speed;//移动速度
public Vector3 moveDirction;//设置移动反向
private Transform groundCheck;//地面检测
private float groundDistance = 0.1f;//与地面的距离
public LayerMask groundMash;
public float jumpForce = 3f;//跳跃力度
public Vector3 velocity;//设置玩家Y轴的一个冲量变化(力)
public float gravity = -20f;//设置重力
private bool isJump;//判断是否在跳跃
public bool isRun;//判断是否在奔跑
private bool isGround;
[SerializeField] private float slopeForce = 6.0f;//走斜坡时施加的力度
[SerializeField] private float slopeForceRayLength = 2.0f;//斜坡射线长度(自定义量)
[Header("键位设置")]
[SerializeField] [Tooltip("奔跑按键")] private KeyCode runInputName;//奔跑键位
[SerializeField] [Tooltip("跳跃按键")] public string jumpInputName = "Jump";
private void Start()
{
characterController = GetComponent<CharacterController>();
runInputName = KeyCode.LeftShift;
groundCheck = GameObject.Find("Player/CheckGround").GetComponent<Transform>();
}
private void Update()
{
CheckGround();
Move();
}
public void Move()
{
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
isRun = Input.GetKey(runInputName);
speed = isRun ? runSpeed : walkSpeed;
moveDirction = (transform.right * h + transform.forward * v).normalized;
characterController.Move(moveDirction * speed * Time.deltaTime);//移动
if (isGround == false) { velocity.y += gravity * Time.deltaTime; }
characterController.Move(velocity * Time.deltaTime);
Jump();
//如果处在斜坡上
if (OnSlpe())
{
characterController.Move(Vector3.down * characterController.height / 2 * slopeForce * Time.deltaTime);
}
}
public void Jump()
{
isJump = Input.GetButtonDown(jumpInputName);
if (isJump && isGround)
{
velocity.y = Mathf.Sqrt(jumpForce * -2f * gravity);
}
}
public void CheckGround()
{
isGround = Physics.CheckSphere(groundCheck.position, groundDistance, groundMash.value);
if (isGround && velocity.y <= 0)
{
velocity.y = -2f;
}
}
public bool OnSlpe()
{
if (isJump)
return false;
RaycastHit hit;//向下打出射线(检测是否在斜坡上)
if (Physics.Raycast(transform.position, Vector3.down, out hit, characterController.height / 2 * slopeForceRayLength))
{
if (hit.normal != Vector3.up)
{
return true;
}
}
return false;
}
}