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

About Vector3 (If statement)

Discussion in 'Scripting' started by DoruKs1, Jun 26, 2015.

  1. DoruKs1

    DoruKs1

    Joined:
    Jan 14, 2015
    Posts:
    28
    Hello:
    I was trying to make camera's x stay between 5 and -5. (as example) And I know what I must do. And I did! Check out!
    Code (CSharp):
    1. public Transform atmost;
    2. public Transform atleast;
    3.  
    4. atleast = transform.Translate (-5,0,0);
    5. atmost = transform.Translate (5,0,0);
    6. if(atmost += transform.Translate(5,0,0))
    7.         {
    8.             atmost == transform.Translate(5,0,0);
    9.         }
    10.  
    11.         if(atleast -= transform.Translate(-5,0,0))
    12.         {
    13.             atleast == transform.Translate(-5,0,0);
    14.         }

    Is it wrong?
    Do you have a better code?
    Please share!

    /thanks/
     
  2. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    that's wrong... the += and -= operators return a value so long as the two operands are the same type (or they can be implicitly converted), so those ifs are always going to be true because if(something) is true so long as "something" isn't null. In order for the above code to return null it would have had to error so it wouldn't work anyway.

    also, transform.Translate(...) doens't have a return type so the assignments at the top wont work and should be throwing errors...


    not to mention it's not even a valid file structure for either js or c#
     
  3. DoruKs1

    DoruKs1

    Joined:
    Jan 14, 2015
    Posts:
    28
    Hey! Another question:
    You can see those atmost and atleast , right? I'm trying to give them a vector 3 x,y,z. So... How?
    I'm sure these don't work:
    Code (CSharp):
    1. atleast = transform.Translate (-5,0,0);
    2. atmost = transform.Translate (5,0,0);
     
  4. Dantus

    Dantus

    Joined:
    Oct 21, 2009
    Posts:
    5,667
    No they are also wrong. You translate the position like that two times. Once 5 units along the negative x axis and than back.
    http://docs.unity3d.com/ScriptReference/Transform.Translate.html

    If you want to keep it within -5 and 5, you can do something like that:
    Code (csharp):
    1. Vector3 position = transform.position;
    2. position.x = Mathf.Clamp (position.x, -5, 5);