Page 1 of 1

StandardBarkUI.cs crash fix if scene is shutdown

Posted: Mon Oct 26, 2020 2:10 pm
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);

                }
            }
        }

Re: StandardBarkUI.cs crash fix if scene is shutdown

Posted: Mon Oct 26, 2020 2:22 pm
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.

Re: StandardBarkUI.cs crash fix if scene is shutdown

Posted: Mon Oct 26, 2020 11:46 pm
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

Re: StandardBarkUI.cs crash fix if scene is shutdown

Posted: Tue Oct 27, 2020 8:23 am
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.