NullReferenceException - WorldToScreenPoint

I’m trying to display a GUI box at the location of some Transforms in a list. The error line is:

Vector3 thePosition = Camera.main.WorldToScreenPoint(trigger.position);

The list definitely has transforms inside it.


NullReferenceException

UnityEngine.Camera.WorldToScreenPoint (Vector3 position) (at C:/BuildAgent/work/f724c1acfee760b6/Runtime/ExportGenerated/Editor/Graphics.cs:632)
InteractableTargets.DisplayTargets () (at Assets/_Scripts/Managers/GUIManager/InteractableTargets.cs:87)
InteractableTargets.OnGUI () (at Assets/_Scripts/Managers/GUIManager/InteractableTargets.cs:73)


private bool isEnabled;

public List<Transform> interactables;

//=======================================

void OnGUI()
{
	if (isEnabled)
	{
		DisplayTargets();
	}
}

//=======================================

void DisplayTargets()
{
	foreach(Transform trigger in interactables)
	{
		Vector3 thePosition = Camera.main.WorldToScreenPoint(trigger.position);
		
		GUI.Box(new Rect(thePosition.x-(50/2), Screen.height-thePosition.y-(50/2), 50, 50), trigger.name);
	}
}

2 Answers

2

Either trigger is null or Camera.main is null.

You're right. It should have been "PlayerChar.PLAYER.camera.WorldToScreenPoint(trigger.position)". Thanks.

I tried this script and it worked fine. It only gave an error when the camera tag was changed to something different from “MainCamera” - but the error was a little different:

NullReferenceException
UnityEngine.Camera.ScreenPointToRay (Vector3 position) (at C:/BuildAgent/work/842f9557127e852/Runtime/ExportGenerated/Editor/UnityEngineCamera.cs:267)
ListTargets.Update () (at Assets/Standard Assets/Scripts/ListTargets.cs:18)

The error message started equal, but the Editor script listed is UnityEngineCamera.cs instead of Graphics.cs.

Check the camera tag; if it’s ok, verify what exactly is on lines 87 and 73 of your script (doesn’t match with the code snippet showed above).