I get the folliwng error- “NullReferenceException: Object reference not set to an instance of an object”,
and it refers me to the following line in my code-
" if (!Touchscreen.current.primaryTouch.press.isPressed) ".
Update-
If I erase those line, the error occures again, and it refers me to the next line that includes “Touchscreen”.
The game works fine.
Any advice?
Thanks!
Aviv
1 Like
Paste in your complete script and we’ll take a look.
2 Likes
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class BallHandler : MonoBehaviour
{
[SerializeField] private GameObject ballPrefab;
[SerializeField] private Rigidbody2D pivot;
[SerializeField] private float detachDelay;
[SerializeField] private float respawenDelay;
private Camera mainCamera;
private Rigidbody2D currentBallRB;
private SpringJoint2D currentBallSpringJoint;
private bool isDragging;
void Start()
{
mainCamera=Camera.main;
SpawnNewBall();
}
void Update()
{
if (currentBallRB==null) {return;}
if (!Touchscreen.current.primaryTouch.press.isPressed)
{
if (isDragging)
{
LaunchBall();
}
isDragging=false;
return;
}
Vector2 touchPosition=Touchscreen.current.primaryTouch.position.ReadValue();
Vector3 wordposition = mainCamera.ScreenToWorldPoint(touchPosition);
currentBallRB.position= wordposition;
isDragging=true;
currentBallRB.isKinematic=true;
}
private void LaunchBall()
{
currentBallRB.isKinematic=false;
currentBallRB=null;
Invoke(nameof(DetachBall),detachDelay);
}
private void DetachBall()
{
currentBallSpringJoint.enabled= false;
currentBallSpringJoint= null;
Invoke(nameof(SpawnNewBall),respawenDelay);
}
private void SpawnNewBall()
{
GameObject ballInstance = Instantiate(ballPrefab, pivot.position, Quaternion.identity);
currentBallRB=ballInstance.GetComponent<Rigidbody2D>();
currentBallSpringJoint= ballInstance.GetComponent<SpringJoint2D>();
currentBallSpringJoint.connectedBody=pivot;
}
}
1 Like
The code looks correct. Have you enabled Simulate Touch Input From Mouse or Pen in the Input Debugger? (Window/Analysis/InputDebugger) TouchScreen will be null if this is not done.
2 Likes
Yes, it’s enabled.
Is there any other place in which I can see if the thouchscreen is null?
1 Like
Solved! (but not satisfied)
The error occurs only when I am in game mode. I does not occur when I’m in the simulator.
Thank you Brian!
Aviv
1 Like
Lol, that happens to me all the time, I get frustrated when the game doesn’t work in the game view, and then finally realize that I need to be in the simulator
.
Just remember when doing these types of touch inputs like in the course, you can’t use the game view to test, only the simulator
1 Like
The simulation of the touch screen, enabling TouchScreen is specifically in the Simulator, not the Game window. It simply doesn’t exist in the Game window. That’s a Unity issue.