Camera.main 执行光线投射时为空

Camera.main is null when performing raycast

产生错误的代码:

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

它说这个字符串有问题:

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

错误:

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

确保您的场景中有一个活动的游戏对象,其中包含 Camera 组件和标签“MainCamera”


(来源:unity3d.com

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

Select 然后将 Camera GameObject 的标签更改为 MainCamera。

如果你不希望你的相机在 MainCamera 标签中,你也可以直接用 GameObject.Find 找到机智然后从中获取 Camera 组件。

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

如果您没有将默认的“主相机”游戏对象添加到场景并在运行时对其进行初始化,那么您应该如何正确地做到这一点:

//This is needed in order for UnityEngine.Camera.main... to work
public const string CameraGameObjectName = "MainCamera";

初始化方法的内容:

GameObject cameraGameObject = new GameObject(CameraGameObjectName);
cameraGameObject.tag = CameraGameObjectName;
UnityEngine.Camera camera = cameraGameObject.AddComponent<UnityEngine.Camera>();
Transform cameraPosition = cameraGameObject.GetComponent<Transform>();

之后您可以通过以下方式从任何地方访问它:

UnityEngine.Camera.main.