Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

BUG: Bounds doesn't work as auto-implemented properties (2020.1.11f1)

Discussion in 'Scripting' started by lassade, Mar 12, 2021.

  1. lassade

    lassade

    Joined:
    Jan 27, 2013
    Posts:
    127
    Code (CSharp):
    1. public Bounds someBounds { get; private set; }
    2.  
    3. ...
    4.  
    5. // Wont work
    6. someBounds.Encapsulate(otherBoundsOrPoint);
    7.  
    8. // You will have to
    9. temp = someBounds;
    10. temp.Encapsulate(otherBoundsOrPoint);
    11. someBounds = temp;
    12.  
    13. // or decalre bounds as
    14. Bounds _someBoundsInternal;
    15. public Bounds someBounds => _someBoundsInternal;
    This one made made me cry a bit ...

    As far I remember this used to work, or it always broken like this and I never stumble upon this bug ?!?!?
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,735
    It's the same issue as affects any property that returns a struct: properties are actually a pair of get/set functions masquerading as a variable, and changing variables on the copy you receive from the "get" will not affect the main object. So when you call this:
    Code (csharp):
    1. someBounds.Encapsulate(other);
    What the compiler sees is this:
    Code (csharp):
    1. GetSomeBounds().Encapsulate(other);
    So GetSomeBounds() returns a copy of the Bounds object (because structs are passed by value), you call Encapsulate which affects that returned copy, but then that copy is lost to the ether because nothing was there to catch it.

    This is the same reason that
    transform.position.x = 5f;
    doesn't work. position is a property, the "get" accessor generates/returns a copy of the Vector3 struct, and when .x is changed that doesn't apply to the source.

    It's possible that:
    1) you may be remembering using a public member this way that WASN'T a property; that wouldn't have this limitation.
    2) you may have used Encapsulate way back in the days of Javascript, where this would I think actually work. JS had some sort of weird convenience hack that allowed transform.position.x = 5; to work, and I assume the same would be true of other properties
    3) There's a very tiny chance that a long long time ago, Bounds might have been a class and not a struct, and this logic would work fine on a class. (I looked back as far as the docs have history, which is Unity 5.2, and it's a struct then, so it'd have been >5 years ago if this is the case. And I don't think it is)
     
    lassade and Kurt-Dekker like this.
  3. lassade

    lassade

    Joined:
    Jan 27, 2013
    Posts:
    127
    Oh, makes sense thanks!