Skip to content

Commit 00b7404

Browse files
Merge pull request #3024 from StephenHodgson/vNEXT-Camera
Fixed CameraCache fail if no camera tagged as main camera.
2 parents de4febd + 9247e43 commit 00b7404

File tree

1 file changed

+43
-1
lines changed

1 file changed

+43
-1
lines changed

Assets/MixedRealityToolkit/_Core/Utilities/CameraCache.cs

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,49 @@ public static class CameraCache
1616
/// <summary>
1717
/// Returns a cached reference to the main camera and uses Camera.main if it hasn't been cached yet.
1818
/// </summary>
19-
public static Camera Main => cachedCamera == null ? Refresh(Camera.main) : cachedCamera;
19+
public static Camera Main
20+
{
21+
get
22+
{
23+
var mainCamera = cachedCamera == null ? Refresh(Camera.main) : cachedCamera;
24+
25+
if (mainCamera == null)
26+
{
27+
// No camera in the scene tagged as main. Let's search the scene for a GameObject named Main Camera
28+
var cameras = Object.FindObjectsOfType<Camera>();
29+
30+
switch (cameras.Length)
31+
{
32+
case 0:
33+
return null;
34+
case 1:
35+
mainCamera = Refresh(cameras[0]);
36+
break;
37+
default:
38+
// Search for main camera by name.
39+
for (int i = 0; i < cameras.Length; i++)
40+
{
41+
if (cameras[i].name == "Main Camera")
42+
{
43+
mainCamera = Refresh(cameras[i]);
44+
break;
45+
}
46+
}
47+
48+
// If we still didn't find it, just set the first camera.
49+
if (mainCamera == null)
50+
{
51+
Debug.LogWarning($"No main camera found. The Mixed Reality Toolkit used {cameras[0].name} as your main.");
52+
mainCamera = Refresh(cameras[0]);
53+
}
54+
55+
break;
56+
}
57+
}
58+
59+
return mainCamera;
60+
}
61+
}
2062

2163
/// <summary>
2264
/// Set the cached camera to a new reference and return it

0 commit comments

Comments
 (0)