执行raycast时Camera.main为null [英] Camera.main is null when performing raycast

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

问题描述

产生错误的代码:

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查找机智,然后从中获取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";
        }
    }
}

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

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