Ошибка MissingComponentException
Я решил попробовать новую версию Unity и написал код который работает в прошлой. Теперь мне выдаёт ошибку: MissingComponentException: There is no 'CharacterController' attached to the "Player" game object, but a script is trying to access it. You probably need to add a CharacterController to the game object "Player". Or your script needs to check if the component is attached before using it. UnityEngine.CharacterController.Move (UnityEngine.Vector3 motion) (at :0)
Код:
public float _speed = 0.6f;
private CharacterController _characterController;
private void Start()
{
_characterController = GetComponent<CharacterController>();
if(_characterController == null)
Debug.Log("CharacterController is NULL");
}
private void Update ()
{
float deltaX = Input.GetAxis("Horizontal") * _speed;
float deltaZ = Input.GetAxis("Vertical") * _speed;
Vector3 movement = new Vector3(deltaX, 0, deltaZ);
movement = Vector3.ClampMagnitude(movement, _speed);
movement *= Time.deltaTime;
movement = transform.TransformDirection(movement);
_characterController.Move(movement);
}
P.S. методом тыка я выяснил, что дело в самой последней строчке, но при любом её изменении скрипт отказывается работать.
Ответы (1 шт):
Иду на помощь!
в строке private CharacterController _characterController; вы создали поле
в строке _characterController = GetComponent<CharacterController>(); вы выдали полю значение
в проверки ниже Вы уверены что не получали данный Лог?
if(_characterController == null)
Debug.Log("CharacterController is NULL");
Советую использовать явные "контракты", гарантию того что компонент будет присутствовать а не делать проверку на его наличие, я предполгаю что данный компонент отсутствует на обьекте и у вас выходит данное сообщение в консоле CharacterController is NULL
Создание "контракта" происходит путём добавления атрибута [RequireComponent(typeof(CharacterController))] в обьекте где он необходим
Пример из документации Unity:
using UnityEngine;
// PlayerScript requires the GameObject to have a Rigidbody component
[RequireComponent(typeof(Rigidbody))]
public class PlayerScript : MonoBehaviour
{
Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
rb.AddForce(Vector3.up);
}
}