I am trying to change the colour of the 2D star sprite below with the following code:
When I run the program only the colour of Sprites-Default gets changed and the star disappears:
Can anyone help?
I am trying to change the colour of the 2D star sprite below with the following code:
When I run the program only the colour of Sprites-Default gets changed and the star disappears:
Can anyone help?
The following script is a working example of how to change the color of a sprite on Start. You can manipulate it to help you.
using UnityEngine;
using System.Collections;
public class ColorChaneg : MonoBehaviour {
public bool changeColor;
// Use this for initialization
void Start ()
{
changeColor = true;
}
// Update is called once per frame
void Update ()
{
if (changeColor) {
gameObject.GetComponent<SpriteRenderer> ().color = new Color (255f, 0f, 1, 1);
}
}
}
Thank you, a working example is always worth its weight in gold.
No problem. Remember, though, that the color will stay whatever color you set in the update based on the if statement for the duration of the game.
So if you wanted to change to green, you would change your if statements around.
public bool changeColorRed = false;
public bool changeColorGreen = false;
public bool changeColorBlue = false;
// Use this for initialization
void Start ()
{
if (someThing == true) {
changeColorRed = true;
}
if (someOtherThing == true) {
changeColorGreen = true;
}
if (yetAnotherThing == true) {
changeColorBlue = true;
}
}
// Update is called once per frame
void Update ()
{
if (changeColorRed) {
gameObject.GetComponent<SpriteRenderer> ().color = new Color (255f, 0f, 0, 1);
}
if (changeColorBlue) {
gameObject.GetComponent<SpriteRenderer> ().color = new Color (0f, 0f, 255f, 1);
}
if (changeColorGreen) {
gameObject.GetComponent<SpriteRenderer> ().color = new Color (0f, 255f, 0, 1);
}
You could even go so far as to assign the rgba to variables and do a random.range on them so you get random colors on each start.
*This is rough, untested code. It should give you an idea of how to manipulate the colors, though. I don’t think you can just say Yellow and it work, but I’ve seen code in the Unity docs about something like that, so maybe I’m wrong.
Also, a more elegant solution would create a new method and call that method from start, rather than constantly forcing the color on update.
Also, also, I’m not sure how much the A is going to change your colors. I’ve not played with it much. The color numbers are RGBA, A being the opacity of the color, IIRC.