-1

I'm a new programmer and I was following some tutorial on YouTube but I am having difficulty making it work.

Here's the error I get: NullReferenceException: Object reference not set to an instance of an object Moving.Update () (at Assets/Moving.cs:39)

Here's the code:

public class Moving : MonoBehaviour
{
  public float mouseSensitivity = 100.0f;
  public float clampAngle = 80.0f;

  private float rotY = 0.0f; // rotation around the up/y axis
  private float rotX = 0.0f; // rotation around the right/x axis

  public GameObject player;
  public CharacterController controller;
  public float speed = 6f;

  void Start()
  {
      Cursor.lockState = CursorLockMode.Locked;
      Vector3 rot = transform.localRotation.eulerAngles;
      rotY = rot.y;
      rotX = rot.x;
  }

  void Update()
  {
      float mouseX = Input.GetAxis("Mouse X");
      float mouseY = -Input.GetAxis("Mouse Y");

      rotY += mouseX * mouseSensitivity * Time.deltaTime;
      rotX += mouseY * mouseSensitivity * Time.deltaTime;

      rotX = Mathf.Clamp(rotX, -clampAngle, clampAngle);

      Quaternion localRotation = Quaternion.Euler(rotX, rotY, 0.0f);
      transform.rotation = localRotation;
      transform.parent.transform.Rotation = Quaternion.Euler(rotX, rotY, 0.0f);

      float horizontal = Input.GetAxisRaw("Horizontal");
      float vertical = Input.GetAxisRaw("Vertical");
      Vector3 Direction = (player.transform.forward * vertical + player.transform.right * horizontal).normalized;

      controller.Move(Direction * speed * Time.deltaTime);

  }
}

I'm using unity 2020.3.37

John Doe
  • 300
  • 2
  • 11
  • 1
    Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) –  Aug 16 '22 at 23:10
  • 1
    Welcome to SO! Game development requires _a lot of research._ Did you perform any before posting? What you are experiencing is a very common problem in the world of C# alone. Good luck! –  Aug 16 '22 at 23:12
  • Unity specific help for NRE and useful debugging tips [Unity NRE and Debugging](https://stackoverflow.com/a/71215863/1679220) – hijinxbassist Aug 16 '22 at 23:33
  • i have tried many tthings but can't find whats wrong – DoudeSauce Aug 16 '22 at 23:51
  • Either player or controller is null (maybe both). Check in the inspector – hijinxbassist Aug 17 '22 at 00:53

1 Answers1

0

You haven't provided all the code so I can't exactly know which line is 39 but I think you are getting this error because your transform doesn't have a parent so this line is causing the error.

transform.parent.transform.Rotation = Quaternion.Euler(rotX, rotY, 0.0f);

So first make sure you have assigned the values for player and controller in the inspector then make sure either your object with Moving.cs attached to it have a parent or try remove or change the line of code that is trying to get the transform.parent.

Armin
  • 576
  • 6
  • 13