Toggle Bark UI based on camera distance

Announcements, support questions, and discussion for the Dialogue System.
Post Reply
fr4231
Posts: 20
Joined: Sun Nov 28, 2021 9:44 am

Toggle Bark UI based on camera distance

Post 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!
User avatar
Tony Li
Posts: 21681
Joined: Thu Jul 18, 2013 1:27 pm

Re: Toggle Bark UI based on camera distance

Post 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;
    }
}
fr4231
Posts: 20
Joined: Sun Nov 28, 2021 9:44 am

Re: Toggle Bark UI based on camera distance

Post by fr4231 »

The second method worked perfectly, thank you!
User avatar
Tony Li
Posts: 21681
Joined: Thu Jul 18, 2013 1:27 pm

Re: Toggle Bark UI based on camera distance

Post by Tony Li »

Happy to help!
Post Reply