Page 1 of 1

Toggle Bark UI based on camera distance

Posted: Thu Jun 22, 2023 11:52 am
by fr4231
Hi,

I would like to hide the Bark UI if the camera (not the player, but the camera) gets near and enable again if the camera gets further away, in case of the player it would be easy with triggers, sensors, but the camera has no rigidbody and no colliders either. What would be the ideal way to detect the distance between the camera and the bark UI (world space)? Do you have any recommendations? Or is there a built-in function by any chance to avoid situations when the camera gets very close to the bark UI in 3D space and basically blocks the whole view?

Thank you!

Re: Toggle Bark UI based on camera distance

Posted: Thu Jun 22, 2023 3:34 pm
by Tony Li
Hi,

Here are two ideas:

1. You might be using a separate camera for UIs similarly to the setup described in this post. If so, you can increase the value of the Near Clip Plane.

2. If you're not using a separate camera, you can add a script to the bark UI. Something like:

Code: Select all

using UnityEngine;
public class HideCanvasWhenCloseToCamera : MonoBehaviour
{
    public float hideWhenCloserThan = 3f; // Set in inspector.
    
    private Transform cameraTransform;
    private Canvas canvas;
    
    void Awake() 
    {
         cameraTransform = Camera.main.transform; // Assumes scene has camera tagged MainCamera.
         canvas = GetComponent<Canvas>(); // Assumes this GO has a Canvas.
     }
    
    void Update()
    {
        var distance = Vector3.Distance(this.transform.position, cameraTransform.position);
        canvas.enabled = distance > hideWhenCloserThan;
    }
}

Re: Toggle Bark UI based on camera distance

Posted: Fri Jun 23, 2023 5:01 am
by fr4231
The second method worked perfectly, thank you!

Re: Toggle Bark UI based on camera distance

Posted: Fri Jun 23, 2023 8:06 am
by Tony Li
Happy to help!