StandardBarkUI.cs crash fix if scene is shutdown

Announcements, support questions, and discussion for the Dialogue System.
Post Reply
rakkar
Posts: 51
Joined: Mon Jan 13, 2020 10:39 pm

StandardBarkUI.cs crash fix if scene is shutdown

Post by rakkar »

It is inefficient to check Camera.main as this searches every object in the scene for a string comparison. Reduced to a single check
Camera.main can return null while the scene is shutting down

Code: Select all

 protected virtual void Update()
        {
            if (keepInView && isPlaying)
            {
                // KevinJ: Check camera.main
                Camera mainCamera = Camera.main;
                if (mainCamera != null)
                {

                    //var pos = Camera.main.WorldToViewportPoint(canvas.transform.position);
                    var pos = mainCamera.WorldToViewportPoint(canvas.transform.position);
                    pos.x = Mathf.Clamp01(pos.x);
                    pos.y = Mathf.Clamp01(pos.y);
                    //canvas.transform.position = Camera.main.ViewportToWorldPoint(pos);
                    canvas.transform.position = mainCamera.ViewportToWorldPoint(pos);

                }
            }
        }
User avatar
Tony Li
Posts: 22051
Joined: Thu Jul 18, 2013 1:27 pm

Re: StandardBarkUI.cs crash fix if scene is shutdown

Post by Tony Li »

In older versions of Unity, that's correct. In newer versions, Camera.main uses a cached lookup, so it's not inefficient. (Similarly, a GameObject's transform property is no longer inefficient.)

However, you are absolutely correct about doing a null check. I'll add that. Thank you.
rakkar
Posts: 51
Joined: Mon Jan 13, 2020 10:39 pm

Re: StandardBarkUI.cs crash fix if scene is shutdown

Post by rakkar »

Thanks for taking this fix. Unity 2020.2 makes this optimization. It's still in beta as of the time of this posting, by our standards meaning it's still in alpha.

We internally subtract 1 from Unity's official version.

Alpha = Prealpha
Beta = Alpha
Normal release = Beta
Long Term Support = Normal release
User avatar
Tony Li
Posts: 22051
Joined: Thu Jul 18, 2013 1:27 pm

Re: StandardBarkUI.cs crash fix if scene is shutdown

Post by Tony Li »

I agree with you. I don't prefer to use Camera.main directly, but there are some projects that change cameras mid-scene. If we cache it in Start(), it may not be the correct Camera.main every time Update() runs. But that's why the method is virtual, so you can override it in a subclass if you want to cache Camera.main.

Thank you again for pointing out any issues like this, or the question you have about text auto-scrolling. I really appreciate it, as your feedback helps improve the Dialogue System for everyone.
Post Reply