Why Null Error?

Hello I keep gettin null error. I don’t know how to solve. Code is the exact same. Can you help ?

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

public class PlayerController : MonoBehaviour
{
    private Camera mainCamera;

    void Start()
    {
        mainCamera = Camera.main;
    }

    // Update is called once per frame
    private void Update()
    {
        if (Touchscreen.current.primaryTouch.press.isPressed)
        {

            Vector2 touchPos = Touchscreen.current.primaryTouch.position.ReadValue();

            print(touchPos);

            Vector3 worldPosition = mainCamera.ScreenToWorldPoint(touchPos);

            print(worldPosition);
        }
    }
}

Can you share the error message? It usually tells the exact script and code line where the error is ocurring.

Thanks for the reply. I even copied from the source code but still getting the error.

btw error line is the if statement line

That means Unity is not finding Touchscreen somehow. Do you have any red squiggly lines in any part of your code? Maybe on the UnityEngine.InputSystem namespace in the upper part of the screen?

You could try creating a blank script and see if that solves the issue. Adding the new input system namespace seems to be a bit buggy and sometimes Unity doesn’t recognize it from the start, but creating a blank script seems o force it to recognize it sometimes.

I tired to create fresh script, added namespace first then pasted the exact class again but still the same error. I don’t see any red line under any line.

But I guess I found the problem. At the start of the course, I was using the alpha version of unity and could not install device simulator. I was working on game window. I think there is an issue with clicking game view not the simulator view. I switched to LTS version and installed device simulator. Now I don’t see any error.

Thanks for the quick replies.

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms