How do I change one value, to another, over a time period?

Okay this is a very noob question but...

I want to write a script that allows me to change one value, in this case the "amount" value of a effect I have, to another value... over a time period... also I would like to be able to control this time period (i.e how quickly it does it).

I imagine this is a very easy and noob thing to ask. But hay! gotta start somewhere.

var ctrl : TypeOfObjectToChangeValueOf;
var duration : float;
var startValue : float;
var endValue : float;

function Start() {
    StartCoroutine(ChangeValue());
}

function ChangeValue() {
    var pointInTime : float = 0.0;
    while (pointInTime <= duration) {
    	ctrl.nameOfPropertyToChange = Mathf.Lerp(startValue, endValue, pointInTime / duration);
    	pointInTime += Time.deltaTime;
    	yield 0;
    }
}

Of course TypeOfObjectToChangeValueOf must be replaced by the script type or component type and nameOfPropertyToChange to the property name that must be changed. If you want to change values other than floats:

  • For Colors, change the float behind startValue, endValue to Color and replace Mathf with Color.
  • For Vector3, change the float behind startValue, endValue to Vector3 and replace Mathf with Vector3.

So you can read more about this, assuming you're changing from a source to a target value, the term you're looking for is Interpolation. There are many ways to change said value, depending on how you want the progression. Take a look at Unity's own Mathf, or at the wiki's Mathfx.

you have many ways to do this. you can use animationcurves or coroutines with yield to execute code over time and the above example is a good one. if you multiply any number with time.deltaTime that value is the ammount of change in one second. calculations are not hard for other speeds. if you need to change speed or ... the best way is to use animationCuvres. don't forget to use curve editor in window menu. you don't need to do all of it programaticly