Hi!
I have a subscene with a Billboard HUD on each entity. The issue is, I can’t seem to reference Camera.main in there, and therefore both the Billboard and the Canvas won’t work.
Is there a good way to do this?
Hi!
I have a subscene with a Billboard HUD on each entity. The issue is, I can’t seem to reference Camera.main in there, and therefore both the Billboard and the Canvas won’t work.
Is there a good way to do this?
Several ways to always have access to your MainCamera. You could create a custom cameraController that is a singleton. This would allow you access at anytime, from anywhere.
Or , at least cache a ref to it somehwere that you can get to from anywhere with ease.
That doesn’t work either.
I’ve now got this singleton:
public class CameraProvider : MonoBehaviour
{
public Camera mainCamera;
public static CameraProvider Instance
{
get; private set;
}
private void Awake()
{
// If there is an instance, and it's not me, delete myself.
if (Instance != null && Instance != this)
{
Destroy(this);
}
else
{
Instance = this;
mainCamera = Camera.main;
}
}
public Camera MainCam()
{
if (mainCamera == null)
{
mainCamera = Camera.main;
}
return mainCamera;
}
}
And I’m using it inside the subscene like this:
[RequireComponent(typeof(Canvas))]
public class Billboard : MonoBehaviour
{
[SerializeField] private Camera targetCamera;
[SerializeField] private GameObject targetObject;
private Canvas canvas;
void Start()
{
canvas = GetComponent<Canvas>();
if (targetCamera == null)
{
targetCamera = CameraProvider.Instance.MainCam();
canvas.worldCamera = targetCamera;
}
if (targetObject == null)
{
targetObject = gameObject;
}
}
// Update is called once per frame
void Update()
{
if (targetCamera == null)
{
targetCamera = CameraProvider.Instance.MainCam();
canvas.worldCamera = targetCamera;
}
if (targetCamera != null)
{
gameObject.transform.LookAt(this.targetCamera.transform, Vector3.up);
}
}
}
However, as you can see, the camera isn’t getting set:
You’re not baking your Billboard component to a ECS component