- Home /
Change a float smooth
How can i change a float value to another smoothly?
e.g:
public string number 10;
void update() {
if(Input.GetKeyDown(KeyCode.G)) {
number += 10;
}
}
and the number increases 1 per frame for e.g, how can i do that?
Answer by clunk47 · Oct 04, 2013 at 11:35 PM
Well you need to use an float, not a string. You weren't completely specific, so here's an example of how to move from one number to another by keypress. In this example you toggle a boolean to determine whether or not your number increases. It will stop if you change the boolean to false. Hope this helps.
using UnityEngine;
using System.Collections;
public class Example : MonoBehaviour
{
float num = 0;
float max = 1000;
float increment = 1f;
string label;
bool increase = false;
void Update()
{
label = num.ToString ();
if(increase && num < max)
num += increment;
if(Input.GetKeyDown (KeyCode.E))
increase = !increase;
}
void OnGUI()
{
GUILayout.Label(label);
}
}
Answer by tw1st3d · Oct 04, 2013 at 11:35 PM
Here, try this. You use Time.deltaTime for the smoothness, and GetKey instead of GetKeyDown to determine if it's being held instead of pressed once and then waiting for you to press it again.
using UnityEngine;
using System.Collections;
public class SmoothIncrease : MonoBehavior
{
protected int number = 100;
public void Update()
{
if(Input.GetKey(KeyCode.G))
{
number += 1 * Time.deltaTime;
}
}
}
Just noticed you said float, so ins$$anonymous$$d of protected int just do protected float. Sorry about that!
Your answer
Follow this Question
Related Questions
Why my keypad shows 4x the number in input? 2 Answers
Convert positive float to negative? 5 Answers
Smooth value in Input System 0 Answers
float = int / int float value always 0 1 Answer
Having a GUI text as a int 3 Answers