- Home /
Sprite alpha colour not changing via script
I'm a bit of a Unity novice so apologies in advance if I'm missing something really obvious here.
I'm trying to change the alpha of one of my sprites on a key press - if I Debug.Log the alpha of that sprite on the key press it shows the value changing from 0 to 255 (or vice versa on a second key press), but in play mode nothing is changing on the Sprite Renderer itself.
Here are the relevant pieces of code:
private Color redShip;
void Start () {
redShip = GameObject.Find ("RedShip").GetComponent<SpriteRenderer> ().color;
}
void Update(){
if (Input.GetKeyDown (KeyCode.E)) {
FlipShip ();
}
}
void FlipShip(){
print (redShip.a); // Will correctly show the current alpha
if (redShip.a == 0) {
redShip.a = Mathf.Lerp (0, 255, 1);
} else {
redShip.a = Mathf.Lerp (255, 0, 1);
}
print (redShip.a); // Correctly shows the updated alpha, but not visible in Unity itself
}
I've also tried setting it to a temp variable as a full colour and then setting that back to the original Sprite Renderer value, but that didn't seem to make a difference.
Answer by Finjo · Dec 03, 2017 at 08:01 PM
Yep I was being stupid :) I needed to define the variable as a SpriteRenderer instead of a Color. Looks like the value was just being set to a random variable in my code without actually attaching to the SpriteRenderer.
Working code:
private SpriteRenderer redShip;
void Start () {
redShip = GameObject.Find ("RedShip").GetComponent<SpriteRenderer> ();
}
void FlipShip(){
Color tmp = redShip.color;
if (tmp.a == 0) {
tmp.a = Mathf.Lerp (0, 255, 1);
} else {
tmp.a = Mathf.Lerp (255, 0, 1);
}
redShip.color = tmp;
}
The Lerp function isn't working as I intended it, but I'll spend some time looking into that.
Your answer

Follow this Question
Related Questions
What would cause a sprite or texture to be unable to tint its color? 1 Answer
How can I change the Value of a Color through script? 1 Answer
How to change color property of the Sprite Renderer in C# 1 Answer
i changed color of sprite still not changed 3 Answers
I need to store a value that can have "f" in it, but is in a float/ string 0 Answers