unity runtime_error ai_generated true

NullReferenceException: CanvasRaycaster: No camera found for canvas that is set to Screen Space - Overlay

ID: unity/ui-canvas-raycaster-null

Also available as: JSON · Markdown · 中文
94%Fix Rate
86%Confidence
1Evidence
2024-05-14First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
Unity 2022.3 active
Unity 2023.1 active
Unity 2023.2 active
Unity 6000.0 active

Root Cause

A Canvas in Screen Space - Overlay mode requires a camera to render raycasts, but the event camera is null or the canvas is not assigned to any camera.

generic

中文

屏幕空间-叠加模式的 Canvas 需要相机来渲染射线检测,但事件相机为 null 或 Canvas 未分配给任何相机。

Official Documentation

https://docs.unity3d.com/ScriptReference/Canvas-worldCamera.html

Workarounds

  1. 98% success Assign the main camera to the canvas's 'Event Camera' field in the inspector or via code: canvas.worldCamera = Camera.main;
    Assign the main camera to the canvas's 'Event Camera' field in the inspector or via code: canvas.worldCamera = Camera.main;
  2. 95% success Change the canvas render mode to 'Screen Space - Overlay' and ensure there is at least one camera in the scene tagged as 'MainCamera'.
    Change the canvas render mode to 'Screen Space - Overlay' and ensure there is at least one camera in the scene tagged as 'MainCamera'.

中文步骤

  1. Assign the main camera to the canvas's 'Event Camera' field in the inspector or via code: canvas.worldCamera = Camera.main;
  2. Change the canvas render mode to 'Screen Space - Overlay' and ensure there is at least one camera in the scene tagged as 'MainCamera'.

Dead Ends

Common approaches that don't work:

  1. 80% fail

    Screen Space - Camera requires a camera assignment; the error persists if no camera is set.

  2. 70% fail

    The null reference still occurs if the canvas is enabled at any point during the frame.