-1

The contents are as follows.

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

public class PlayerContllor : MonoBehaviour
{
    [SerializeField]
    private float walkspeed;

    private Rigidbody myRigid;

    [SerializeField]
    private float lookSensitivity;

    [SerializeField]
    private float cameraRotationLimit;
    private float currentCameraRotationX = 0;

    [SerializeField]
    private Camera theCamera;
    private Rigidbody myRigid;
    

    // Start is called before the first frame update
    void Start()
    {
        myRigid = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {

        Move();
        CameraRotation();
    }

    private void Move()
    {
        float _moveDirX = Input.GetAxisRaw("Horizontal");
        float _moveDirZ = Input.GetAxisRaw("Vertical");

        Vector3 _moveHorizontal = transform.right * _moveDirX;
        Vector3 _moveVertical = transform.forward * _moveDirZ;

        Vector3 _velocity = (_moveHorizontal + _moveVertical).normalized * walkspeed;

        myRigid.MovePosition(transform.position + _velocity * Time.deltaTime);
    }

    private void CameraRotation()
    {
        float _xRotation = Input.GetAxisRaw("Mouse Y");
        float _cameraRotationX = _xRotation * lookSensitivity;
        currentCameraRotationX += _cameraRotationX;
        currentCameraRotationX = Mathf.Clamp(currentCameraRotationX, - cameraRotationLimit, cameraRotationLimit);

        theCamera.transform.localEulerAngles = new Vector3(currentCameraRotationX, 0f, 0f);

    }
}'''

I wrote this and got an error like this.

please help me avoid errors.

It is to implement the movement of the player and the movement of the character screen up and down with the mouse.

The content of the error is as follows.

unassigned Reference Exception: The variable theCamera of PlayerController has not been assigned. You probably need to assign theCamera variable of the playerController script in the inspector.

Thank you.

Steve B
  • 36,818
  • 21
  • 101
  • 174

1 Answers1

0

As the error suggests, you probably need to assign the variables "theCamera". The error suggests you do this in the editor. Not sure if it shows up there since you made the field private. Consider making it public and drag the camera into its position in the Unity editor. Otherwise you need to initialize the component the same way you do with "myRigid" except you need to search for the camera object.

Edit: Add this in the Start() method.

theCamera = Camera.main;

from: https://docs.unity3d.com/ScriptReference/Camera-main.html

infroz
  • 1,152
  • 2
  • 6
  • 13