Hey, I was following a tutorial on YouTube, and I followed the tutorial word for word, and I keep getting the same error.
NullReferenceException: Object reference not set to an instance of an object
CompassBar.SetMarkerPosition (UnityEngine.RectTransform markerTransform, UnityEngine.Vector3 worldPosition) (at Assets/Scripts/Util/CompassBar.cs:74)
CompassBar.Update () (at Assets/Scripts/Util/CompassBar.cs:32)
here is the script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class CompassBar : MonoBehaviour
{
public RectTransform compassBarTransform;
public RectTransform objectiveMarkerTransform;
public RectTransform northMarkerTransform;
public RectTransform southMarkerTransform;
public Transform cameraObjectTransform;
public Transform objectiveObjectTransform;
void Update()
{
Debug.Log("Update method called.");
// Add detailed null checks and debug logs before calling SetMarkerPosition
if (objectiveMarkerTransform == null)
{
Debug.LogError("objectiveMarkerTransform is not assigned!");
}
else if (objectiveObjectTransform == null)
{
Debug.LogError("objectiveObjectTransform is not assigned!");
}
else
{
SetMarkerPosition(objectiveMarkerTransform, objectiveObjectTransform.position);
}
if (northMarkerTransform == null)
{
Debug.LogError("northMarkerTransform is not assigned!");
}
else
{
SetMarkerPosition(northMarkerTransform, Vector3.forward * 1000);
}
if (southMarkerTransform == null)
{
Debug.LogError("southMarkerTransform is not assigned!");
}
else
{
SetMarkerPosition(southMarkerTransform, Vector3.back * 1000);
}
}
private void SetMarkerPosition(RectTransform markerTransform, Vector3 worldPosition)
{
if (markerTransform == null)
{
Debug.LogError("Marker Transform is not assigned!");
return;
}
if (cameraObjectTransform == null)
{
Debug.LogError("Camera Object Transform is not assigned!");
return;
}
if (compassBarTransform == null)
{
Debug.LogError("Compass Bar Transform is not assigned!");
return;
}
Vector3 directionToTarget = worldPosition - cameraObjectTransform.position;
float angle = Vector2.Angle(new Vector2(directionToTarget.x, directionToTarget.z), new Vector2(cameraObjectTransform.transform.forward.x, cameraObjectTransform.transform.forward.z));
float compassPositionX = Mathf.Clamp(2 * angle / Camera.main.fieldOfView, -1, 1);
markerTransform.anchoredPosition = new Vector2(compassBarTransform.rect.width / 2 * compassPositionX, 0);
Debug.Log($"SetMarkerPosition called for {markerTransform.name} with position {worldPosition}");
}
}