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. Voting for the Unity Awards are OPEN! We’re looking to celebrate creators across games, industry, film, and many more categories. Cast your vote now for all categories
    Dismiss Notice
  3. Dismiss Notice

Vector3Int - wrong value for z component

Discussion in 'Scripting' started by AAAAAAAAAE, Sep 12, 2018.

  1. AAAAAAAAAE

    AAAAAAAAAE

    Joined:
    Jun 8, 2013
    Posts:
    90
    1.png Hi,

    Im using Unity3d 2018..2.0f2 Personal Edition.

    In my script , I'm calculating the value for Vector3Int ind.

    In the Watch window it is clearly showing that the z component value should be 2
    but the z component value for ind.z => 1.

    I cannot understand why this is happening ?

    Please help.
     
  2. AAAAAAAAAE

    AAAAAAAAAE

    Joined:
    Jun 8, 2013
    Posts:
    90
    Hi,
    When i replaced with direct value 2, ind.z = 2;

    i think Vector3Int is ignoring the fraction part as in 0 2.png .5 + 1.5 => 0 + 1 => 1
     
  3. AAAAAAAAAE

    AAAAAAAAAE

    Joined:
    Jun 8, 2013
    Posts:
    90
    Interestingly when i added cp to a new Vector3 with all max values

    and then did Vector3Int.RoundToInt(cp) the answer came out right.
    3.png
     
  4. halley

    halley

    Joined:
    Aug 26, 2013
    Posts:
    1,839
    The whole point of an Integer is that it always continually throws away the fractional part. The fractional part never enters your variables. So yes,
    (int) 0.5 = 0, (int)1.5 = 1, (int)0.5 + (int)1.5 = 1
    . As you found, if you want an integer answer at the end, then convert to integer ONLY at the end, of a computation.
     
    JoeStrout and AAAAAAAAAE like this.
  5. AAAAAAAAAE

    AAAAAAAAAE

    Joined:
    Jun 8, 2013
    Posts:
    90
    So there is no rounding off if casting float to int.

    For some reason i thought rounding off would happen automatically.

    Thanks.
     
  6. halley

    halley

    Joined:
    Aug 26, 2013
    Posts:
    1,839
    Check the specifics on
    Mathf.Floor, Mathf.Ceil, Mathf.Round
    and their
    ~2Int
    varieties. Important to understand how they behave, especially with negative numbers.
     
    AAAAAAAAAE likes this.
  7. AAAAAAAAAE

    AAAAAAAAAE

    Joined:
    Jun 8, 2013
    Posts:
    90
    Thanks for the info. It was worth it.