I want to lerp between colors for multiple components’ color property, like UI-Text, UI-Image, SpriteRenderer, etc…
Therefore it is much more dynamic by dropping the specified component which contains a color property into the public field reference of this script.
public float blinkSpeed = 3f;
public Color startColor = Color.red;
public Color endColor = Color.blue;
private Color currentColor;
public *BASECLASS-WITH-COLOR-PROPERTY* target;
// Update is called once per frame
void Update () {
currentColor = Color.Lerp(startColor, endColor, Mathf.PingPong(Time.time * blinkSpeed, 1f));
target.color = currentColor;
}
That’s not possible as the classes mentioned do not share a common base class which introduces a “color” property. The UI classes Text and Image do have a common base class: “Graphic”. This class introduces a property named “color”. However the SpriteRenderer implements its own color property. There is no common base class. Just like like in this case:
public class ClassA
{
public Color color {get; set;}
}
public class ClassB
{
public Color color {get; set;}
}
Both classes have a property named “color” but they have nothing in common.
The only way would be to use reflection or to simply create conditional code depending on the actual type and create a seperate case for each type you want to support.
ps: this question basically asked for something similar and i suggested the same solution. In this case the question was about the “enabled” property which is also not the same for all components which can be enabled. I’ve posted another example as a comment below that answer of mine which also includes a reflection fallback in case the type isn’t catched earlier.