Author Topic: Possible bug: anchors attached to world objects break on scene unloading  (Read 1339 times)


  • Full Member
  • ***
  • Thank You
  • -Given: 2
  • -Receive: 4
  • Posts: 113
    • View Profile
Simple example: let's say you have a GameObject in your DontDestroyOnLoad hierarchy which you move to various world-space positions you want a UI widget to be anchored to. Internally, that case works like this: a scene-rendering camera is retrieved and used for world to screen pos conversion of position of that GameObject to position of the anchored widget. Example in motion (line endpoints and big white marker are all done this way).

^ WebM, click to open

There is one case where current implementation fails, though, and that's when your game has an "immortal" (DontDestroyOnLoad) UI hierarchy travelling trough multiple scenes, each scene with it's own scene camera. Scene camera used for anchor conversions is fetched on Awake of a widget once, so that camera reference goes null immediately after you load another scene, permanently disabling world space anchoring on a widget.

It's pretty simple to fix, though. Just add this to the top of UIRect.GetLocalPos method:
To this:

  1. protected Vector3 GetLocalPos (AnchorPoint ac, Transform trans)
  2. {
  3.     if (ac.targetCam == null) ac.targetCam = Camera.main;
  4.     ...

With this, UIRect will recover the target camera once it becomes null. Maybe there is more elegant way of doing that, but this fixed our issues with world space anchored widgets becoming inert on every scene load. Might be worth adding to the next patch. :)


  • Administrator
  • Hero Member
  • *****
  • Thank You
  • -Given: 337
  • -Receive: 1171
  • Posts: 22,128
  • Toronto, Canada
    • View Profile
I think calling FindCameraFor would be more appropriate:
  1. if (ac.targetCam == null) FindCameraFor(ac);
That said, you can just broadcast ResetAnchors() to re-evaluate all anchoring cameras. Do it after unloading / reloading your scene.