I am Facing an Issues whenever I play the Game / in Play Mode SCENE.
Warning ( Heavy Exclamation Mark Symbol // Red colored “!” :
NullReferenceException: Object reference not set to an instance of an object
PlayerMovement.ScreenTouch () (at Assets/NewScriptforAsteroid/PlayerMovement.cs:35)
PlayerMovement.Update () (at Assets/NewScriptforAsteroid/PlayerMovement.cs:26)
type or paste code here
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerMovement : MonoBehaviour
{
[SerializeField] private float forceMagnitude;
[SerializeField] private float maxVelocity;
[SerializeField] private float rotationSpeed;
private Rigidbody rb;
private Camera mainCamera;
private Vector3 movementDirection;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
mainCamera = Camera.main;
}
// Update is called once per frame
void Update()
{
ScreenTouch();
KeepPlayerOnScreen();
RotateNoseofPlane();
}
private void ScreenTouch()
{
if (Touchscreen.current.primaryTouch.press.isPressed) //to check: currently touching screen
{
Vector2 tP = Touchscreen.current.primaryTouch.position.ReadValue(); //read on what location/position of screen
//convert the position from screen space to World Space
Vector3 worldPosition = mainCamera.ScreenToWorldPoint(tP);
/* take 0,0 subtract -x,-y */
movementDirection = transform.position - worldPosition;
movementDirection.z = 0f;
movementDirection.Normalize();
}
else
{
movementDirection = Vector3.zero;
}
}
private void FixedUpdate()
{
if(movementDirection == Vector3.zero) { return; }
rb.AddForce(movementDirection * forceMagnitude* Time.deltaTime, ForceMode.Force);
rb.velocity =Vector3.ClampMagnitude(rb.velocity, maxVelocity);
}
void KeepPlayerOnScreen()
{
//Starting with default position
Vector3 newPosition = transform.position;
//convert from world to ViewPort Space
Vector3 viewportPosition_vpP = mainCamera.WorldToViewportPoint(transform.position);
//llleft & right Screen
if (viewportPosition_vpP.x > 1)
{
newPosition.x = -newPosition.x + 0.1f;
}
else if (viewportPosition_vpP.x < 0)
{
newPosition.x = -newPosition.x - 0.1f;
}
// top & bottom of the Screen
if (viewportPosition_vpP.y > 1)
{
newPosition.y = -newPosition.y + 0.1f;
}
else if (viewportPosition_vpP.y < 0)
{
newPosition.y = -newPosition.y - 0.1f;
}
transform.position = newPosition;
}
void RotateNoseofPlane()
{
if (rb.velocity == Vector3.zero) { return; }
Quaternion targetRotation = Quaternion.LookRotation(rb.velocity, Vector3.back);
transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, rotationSpeed* Time.deltaTime);
}
}