How to change UI Image color based on speed
Hello everyone, I'm currently having issues even on finding any reference that allows me to change the color of a UI sprite/Image based on the Rigidbody.velocity.magnitude value. Since the game is a fast parkour-like game and there is a units per second indicator, the effect I'd like to obtain is a bar that changes color (Not increase in size to go from one color to another, but it's just a bland white sprite that has to change from blue to red and eventually purple if it goes over the regular high speed expectations).
I'd really appreciate some documentation of some sort that will allow me to obtain this effect. (I know both C# and JavaScript/Unity Script, so if you only know JavaScript I'll still be able to understand)
Answer by gameplay4all · Feb 22, 2017 at 06:53 PM
Hello,
What I would like to suggest is using a Gradient
. These can easily be setup and customized in the inspector. You can pick a color from the gradient by using the function Gradient.Evaluate()
https://docs.unity3d.com/ScriptReference/Gradient.Evaluate.html This takes in a value from 0, left, to 1, right. Now to get this value you need to know at what speed and beyond, you want the color to be the rightmost color of the gradient. In the example below I called it "maxSpeed"
Gradient speedGradient;
float maxSpeed = 10;
Color GetColorFromSpeed( float speed){
return speedGradient.Evaluate(Mathf.Min(speed/maxSpeed , 1));
}
The Mathf.Min is to make sure higher speeds don't result in errors if you try to evaluate a number higher than 1. I'm not sure if it's needed, though.
Good luck!
-Gameplay4all
Thanks, it worked!
For whoever is less experienced: here's the code I used
public Image speedBar;
public Gradient speedBarColors;
public float maxSpeed = 30;
// Update is called once per frame
void Update ()
{
speedBar.color = speedBarColors.Evaluate($$anonymous$$athf.$$anonymous$$in(GameObject.FindWithTag("Player").GetComponent<Rigidbody>().velocity.magnitude / maxSpeed, 1));
}
Hey one more tip! Functions like FindWithTag
and GetComponent
are really heavy performance wise. So you really don't want to call them multiple times each frame. Try using variables like PlayerRigidBody
and assign them in the Start
function.
Your answer
Follow this Question
Related Questions
How to change GUI label size 1 Answer
Loading Game Crash 1 Answer
Multiplayer Hiding Layer just for Local Player 0 Answers
EditorGUILayout.ObjectField and array 0 Answers