Mouselook Code

Hi everyone.
I am a rookie coder in C# and a rookie with Unity in general.
I’ve been following a first person movement tutorial and in the tutorial he makes the player object not rotate when the camera rotates. This however does not work for me even after copying the code character after character.
Here’s the code:

using System.Collections;

using System.Collections.Generic;

using UnityEngine;



public class MouseLook : MonoBehaviour

{

    public float mouseSpeed = 100f;

    public Transform playerBody;

    float xRotation = 0f;



    void Start()

    {

        Cursor.lockState = CursorLockMode.Locked;

    }

    void Update()

    {

        float mouseX = Input.GetAxis("Mouse X") * mouseSpeed * Time.deltaTime;

        float mouseY = Input.GetAxis("Mouse Y") * mouseSpeed * Time.deltaTime;





        xRotation -= mouseY;

        xRotation = Mathf.Clamp(xRotation, -90f, 90f);



        transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);

        playerBody.Rotate(Vector3.up * mouseX);

    }

}

Thanks in advance for the help!

There’s more to it than just the code in the script. Did you properly assign the playerBody transform? Is this script attached to the correct object?

This is a very important concept in Unity: the code is like 10% of the problem, and the other 90% is having the scene or prefab or whatever other non-code parts lined up the way they need to be, and you want to focus appropriately on understanding that side of things, as it is not optional.

I have selected my Character Controller with the Player Body transform and the man in the video did that too, yet it still rotates the cylinder whilst it does not rotate in the video.

And which object is this MouseLook script attached to? Which object is the cylinder mesh filter/mesh renderer attached to?

I have found the error in my ways.
There was a script connected to the camera AND the object. I have removed the script and it fixed the problem

Apologies for this hinderance

1 Like