Здравствуйте, я написал код вот такой:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(CharacterController))]
public class RelativeMovement : MonoBehaviour
{
[SerializeField] private Transform target;
public float moveSpeed = 6.0f;
private CharacterController _charController;
public float rotSpeed = 15.0f;
public float jumpSpeed = 15.0f;
public float gravity = -9.0f;
public float terminalVelocity = -10.0f;
public float minFall = -1.5f;
private float _vertSpeed;
private ControllerColliderHit _contact;
void Start()
{
_vertSpeed = minFall;
_charController = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update()
{
Vector3 movement = Vector3.zero;
float horInput = Input.GetAxis("Horizontal");
float vertInput= Input.GetAxis("Vertical");
if(horInput != 0|| vertInput != 0)
{
movement.x = horInput*moveSpeed;
movement.z = vertInput*moveSpeed;
movement = Vector3.ClampMagnitude(movement, moveSpeed);
Quaternion tmp = target.rotation;
target.eulerAngles = new Vector3(0, target.eulerAngles.y,0);
movement = target.TransformDirection(movement);
target.rotation = tmp;
Quaternion direction = Quaternion.LookRotation(movement);
transform.rotation = Quaternion.Lerp(transform.rotation, direction, rotSpeed*Time.deltaTime);
}
bool hitGround = false;
RaycastHit hit;
if (_vertSpeed < 0 && Physics.Raycast(transform.position, Vector3.down, out hit))
{
float check = (_charController.height + _charController.radius) / 1.9f;
hitGround = hit.distance <= check;
}
if (hitGround)
{
if (Input.GetButtonDown("Jump"))
{
_vertSpeed = jumpSpeed;
}
else
{
_vertSpeed = minFall;
}
}
else
{
_vertSpeed += gravity * 5 * Time.deltaTime;
if (_vertSpeed < terminalVelocity)
{
_vertSpeed = terminalVelocity;
}
if (_charController.isGrounded)
{
if (Vector3.Dot(movement, _contact.normal) < 0)
{
movement = _contact.normal * moveSpeed;
}
else
{
movement += _contact.normal * moveSpeed;
}
}
}
movement.y = _vertSpeed;
movement *= Time.deltaTime;
_charController.Move(movement);
}
void OnControllerCollliderHit(ControllerColliderHit hit)
{
_contact = hit;
}
}
Все хорошо, C# ошибки не выдает и юнити вроде принял,но стоит персонажу попытаться сойти с платформы, он зависает а консоль выдает такую ошибку:
NullReferenceException: Object reference not set to an instance of an object
RelativeMovement.Update () (at Assets/scripte/RelativeMovement.cs:83)
Я понимаю что ошибка находиться вот в этом фрагменте:
if (Vector3.Dot(movement, _contact.normal) < 0)
А если точнее то в переменной _contact.normal. Но я не знаю как это исправить. Понимаю что накосячил где-то или строчку не ввел,но не могу понять что за строчка и что вообще тут надо написать