Camera.main is null when performing raycast

后端 未结 2 1537
独厮守ぢ
独厮守ぢ 2020-11-28 16:03

Code that generates an error:

void Update()
{
    if (Input.touchCount > 0)
    {
        RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPo         


        
相关标签:
2条回答
  • 2020-11-28 16:20

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

    Tag

    0 讨论(0)
  • 2020-11-28 16:24

    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";
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题