I’m new to Unity, C# and asking for support. i tried to make it so that if the mouse button is pushed it picks up the object and if mouse button is not pushed it drops the object but instead it puts out error
"
NullReferenceException: Object reference not set to an instance of an object
MousePos2D.Update () (at Assets/Scripts/MousePos2D.cs:17)
"
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MousePos2D : MonoBehaviour
{
[SerializeField] private Camera mCam;
public GameObject Curser;
private void Update()
{
Ray ray = mCam.ScreenPointToRay(Input.mousePosition);
RaycastHit raydata = new();
transform.position = raydata.transform.position;
float rayx = ray.origin.x;
float rayy = ray.origin.y - 1.25f;
float rayz = ray.origin.z;
Vector3 Raypos = new Vector3(rayx, rayy, rayz);
transform.position = Raypos;
if (Input.GetMouseButton(0))
{
// this does "raycastHit.transform. = raycastHit.collider.gameObject.transform;" in a jank way
raydata.collider.transform.GetComponent<Rigidbody>().isKinematic = true;
raydata.collider.transform.SetParent(Curser.transform);
}
else IfNotDown();
void IfNotDown()
{
// Input.GetMouseButtonUp doesnt work...
raydata.collider.transform.parent = null;
raydata.collider.transform.GetComponent<Rigidbody>().isKinematic = false;
}
}
}