Reference a variable of another script

I try to setup a coroutine which can change values by time, for example change an alpha value form 0 to 1 in 5 seconds. I thought I can programm it as an extension method and call it from any script, but I don’t know how to tell the coroutine which value it should change. I heard of pointers and that you can’t use them in Unity.

IEnumerator ChangeVariable(float duration,int targetVariable)
{
	float time=0;
	while (time<duration)
	{
		time+=Time.deltaTime;
		targetVariable=time/duration;
		yield return new WaitForEndOfFrame();
	}
	yield return null;
}

targetVariable should be only the adress of the variable this coroutine should change.

You could either pass an enum into the Coroutine that you then use in a switch statement to determine what variable to set. Or, pass the Coroutine a lambda that sets the proper variable:

private IEnumerator ChangeVariable(float duration, Action<float> op){
    float time = 0;
    while (time < duration) {
        time += Time.deltaTime;
        op(time / duration);
        yield return new WaitForEndOfFrame();
    }
    yield return null;
}

// use example, given you have this Color object 
Color color = /* whatever */;
StartCoroutine(ChangeVariable(duration, (val) => color.a = val));
StartCoroutine(ChangeVariable(duration, (val) => color.r = val));

To change different or multiple values, all that needs to change is the lambda

I did not fully understand. But you can call any this function.

.getComponent.StartCoroutine(“ChangeVariable”,3); //call function with your duration
.getComponent.targetVariable //get target Variable

Example Test.cs Script

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test : MonoBehaviour 
{

	public float targetVariable;
	public float duration = 3;

	void Start()
	{
		StartCoroutine ("ChangeVariable",duration);
	}

	void Update()
	{
		Debug.Log (targetVariable);
	}

	public IEnumerator ChangeVariable(float duration)
	{
		float time=0;
		while (time<duration)
		{
			time+=Time.deltaTime;
			targetVariable=time/duration;
			yield return new WaitForEndOfFrame();
		}
		yield return null;
	}
}