执行光线投射时,Camera.main 为空 [英] Camera.main is null when performing raycast

查看:41
本文介绍了执行光线投射时,Camera.main 为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

产生错误的代码:

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);

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

错误:

NullReferenceException: 未将对象引用设置为对象的实例leftScript.Update ()(在 Assets/leftScript.cs:16)

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

推荐答案

在您的代码中唯一可以返回 null 的是 Camera.main.ScreenToWorldPoint.这意味着 Camera.mainnull.要初始化 Camera.main,相机必须具有 MainCamera 标签.

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.

选择 Camera GameObject,然后将标签更改为 MainCamera.

Select the Camera GameObject then change the tag to MainCamera.

如果您不希望您的相机位于 MainCamera 标签中,您也可以直接使用 GameObject.Find 找到 wit,然后从中获取 Camera 组件.

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";
        }
    }
}

这篇关于执行光线投射时,Camera.main 为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆