Hi, I’m relatively new to Unity.
I’ve made a script that when I tap and hold on the screen, the player moves forward, and when I swipe left and right, the player follows it. But the code is getting an error: "NullReferenceException: Object reference not set to an instance of an object PlayerMovement.Update () (at Assets/Scripts/PlayerMovement.cs:17)"
The script: using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMovement: MonoBehaviour { public Rigidbody rb; public float forwardForce = 500f; void Update() { if (Input.touchCount > 0) { Touch t = Input.GetTouch(0); Vector3 tch = Camera.main.ScreenToWorldPoint(t.position); float x = tch.x; PlayerGo(tch, x); } } void PlayerGo(Vector3 tch, float x) { rb.AddForce(0, 0, forwardForce * Time.deltaTime); tch = transform.position; tch.x = x; transform.position = tch; } }
The error is in the line Vector3 tch = Camera.main.ScreenToWorldPoint(t.position);
What I understand from the error is that the function returns a null value.
I’ve debugged and checked that the t.position does not return a null value.
The program plays normally, until I touch the screen and the error appears. What is the problem here?
I should also mention that this is an URP project.
Also, I’ve checked, there are no other classes with the name Camera. Not that I know of.
Thanks in advance. (^_^)
Null reference exception can be a bit tricky to find out, in my experience.
On that line, I see two objects that could produce a NRE:
First, Camera.main.Screen : is there a camera in the scene? Does it have the tag ‘MainCamera’?
If all is fine with Camera, I would check t.position - is there a t object?
You could check whether t sends a null reference by inserting a Debug.Log - for instance
Debug.Log("t : "+t);
If it sends null or a NRE, then your problem is with your t.
Expect to see this error a LOT. It’s easily the most common thing to do when working. Learn how to fix it rapidly. It’s easy. See the above link for more tips.
This is the kind of mindset and thinking process you need to bring to this problem: