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

How to Cap Variables?

Discussion in 'Scripting' started by ColouredPixelsUnity, Sep 9, 2015.

  1. ColouredPixelsUnity

    ColouredPixelsUnity

    Joined:
    Aug 10, 2014
    Posts:
    78
    Hi, I guess this isn't a 2d question, but I would mainly use this for 2D, so why not! My question is how to cap a variable like, your character speeds up the more he runs, but it stops at a certain speed, or the the more you push the space button, the character jumps higher, but stops after the a certain height for example. Thanks for the answers in advance!
     
  2. orb

    orb

    Joined:
    Nov 24, 2010
    Posts:
    3,033
    Mathf.Clamp() and related methods might be what you want in some cases. Give it a variable input, the minimum and the maximum. If you're adding force via physics it's probably better to keep a running total and stop adding when at maximum. Clamping values is neat and tidy when not using physics though.
     
    theANMATOR2b likes this.
  3. ColouredPixelsUnity

    ColouredPixelsUnity

    Joined:
    Aug 10, 2014
    Posts:
    78
    So if I was usin Physics then how would I stop at the max value?
    Ps. Thanks for the first answer, i would just like the know the answer for physics too.
     
  4. orb

    orb

    Joined:
    Nov 24, 2010
    Posts:
    3,033
    ColouredPixelsUnity likes this.