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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Use of "|"

Discussion in 'Scripting' started by Exopole, Mar 19, 2018.

  1. Exopole

    Exopole

    Joined:
    Apr 11, 2017
    Posts:
    3
    Hello !

    In the charactere asset of Unity I saw :
    m_Rigidbody.constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationY | RigidbodyConstraints.FreezeRotationZ;

    I don't known what "|" mean. Someone could explain it to me ?
    Thank a lot :)
     
  2. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
  3. CDMcGwire

    CDMcGwire

    Joined:
    Aug 30, 2014
    Posts:
    133
    It's a bitwise "or" operation. To save space, that constraints variable is probably a single byte of information. To set it, you couldn't use a whole boolean, because that would set all 8 bits to either 1 or 0 (or some similar effect). So instead, each constraint is represented as a different bit of the 8 and they are logically combined.

    For instance:
    XRotation = 00000001
    YRotation = 00000010
    then
    XRot|YRot = 00000011

    meanwhile if it were a bit wise "and" operation
    XRot&YRot = 00000000

    A normal || or && operation works the same logic, but in an all or nothing manner.

    So
    11111110 || 00000010
    is not guranteed to evaluate bitwise, and may result in 00000000 (false), just because both of the last bits were 0. Or, it may evaluate to 11111111 (true) due to either the first bit evaluating to 1, or because at least single bit evaluates to 1.
     
  4. Exopole

    Exopole

    Joined:
    Apr 11, 2017
    Posts:
    3
    Thank you very much
    thank you ! It's help me lot !
     
  5. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    You cannot use a logical OR with integers in C#.

    However, in c, for instance, 2 ints using a logical OR operator would evaluate to true if either was not zero.. no bits are modified, and the result is '1' or '0' (depending on any non-zero or both zeroes).
    :)
     
    Exopole likes this.
  6. CDMcGwire

    CDMcGwire

    Joined:
    Aug 30, 2014
    Posts:
    133
    Glad I could help!