Camera.main is null when performing raycast

旧时模样 提交于 2019-11-26 08:35:30

问题


Code that generates an error:

void Update() {     if (Input.touchCount > 0)     {         RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position), Vector2.zero);         if (hit && hit.collider != null && hit.collider.name == \"leftTapArea\")         {             hit.transform.name = \"Hit\";         }     } } 

It says that something is wrong with this string:

RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position), Vector2.zero);

Error:

NullReferenceException: Object reference not set to an instance of an object leftScript.Update () (at Assets/leftScript.cs:16)


回答1:


The only thing that can return null in your code is Camera.main.ScreenToWorldPoint. It means that Camera.main is null. For Camera.main to be initialized, the camera must have the MainCamera tag.

Select the Camera GameObject then change the tag to MainCamera.

If you don't want your camera to be in the MainCamera tag, you can also find wit directly with GameObject.Find then get the Camera component from it.

Camera cam;  void Start() {     cam = GameObject.Find("NameOfCameraGameObject").GetComponent<Camera>(); }  void Update() {     if (Input.touchCount > 0)     {         RaycastHit2D hit = Physics2D.Raycast(cam.ScreenToWorldPoint(Input.GetTouch(0).position), Vector2.zero);         if (hit && hit.collider != null && hit.collider.name == "leftTapArea")         {             hit.transform.name = "Hit";         }     } } 



回答2:


Make sure you have in your scene an active gameobject with the Camera component and the tag "MainCamera"



来源:https://stackoverflow.com/questions/41659982/camera-main-is-null-when-performing-raycast

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!