c# - Raycast returns null -
code generates 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 wrong string:
raycasthit2d hit = physics2d.raycast(camera.main.screentoworldpoint(input.gettouch(0).position), vector2.zero);
error:
nullreferenceexception: object reference not set instance of object leftscript.update () (at assets/leftscript.cs:16)
the thing can return null in code camera.main.screentoworldpoint
. means camera.main
null
. camera.main
initialized, camera must have maincamera
tag.
select camera gameobject change tag maincamera.
if don't want camera in maincamera tag, can find wit directly gameobject.find
camera
component 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"; } } }
Comments
Post a Comment