- Home /
I can't dynamically change the color of my particles
I'm having a problem changing the color of the particles dynamically. The code below allows me to select any number of colors and put them in a colors array. From there, I randomly select a color in Start() and save that value in myColor. Since it is saved to a global variable, I should be able to use it later right?
Well, this is where it gets tricky: I can assign that color to the material of the Something object. That seems to work fine. Then, I go to KillSomething(). If I Debug.Log myColor, it tells me its whatever color I'm expecting it to be. If I assign it to the particle startColor, though, I get nothing. If I hard code in a specific startColor (as shown below), the particles will show that color.
Why won't temp.startColor = myColor; work? But temp.startColor = Color.red; will?
public class Something : MonoBehaviour {
public Color[] colors;
public Material somethingColor;
public GameObject confetti;
[HideInInspector]
public Color myColor;
void Start(){
this.myColor = colors[Random.Range(0, colors.Length)];
this.gameObject.transform.Find("Somethin/whatever").GetComponent<Renderer>().material.color = myColor;
}
public void KillSomething(){
var c = Instantiate(confetti, transform.Find("Somethin/whatever").position, Quaternion.identity);
var temp = c.transform.Find("Pieces").GetComponent<ParticleSystem>().main;
temp.startColor = Color.red;
Debug.Log(myColor.ToString());
Destroy(c, 2f);
Destroy(gameObject);
}
Answer by thechosenone570 · May 23, 2018 at 01:01 PM
I found the solution. For whatever reason, the alpha in myColor is 0. So, what I did was added a line of code just after I randomly choose the color:
this.myColor = new Vector4(this.myColor.r, this.myColor.b, this.myColor.g, 1);
I don't know why it was assigning that color to the material in the line immediately after it, but whatever. I found a hackish way around it. Hope this helps others that have the same issue in the future
Are you sure that the colors in colors
array had alpha different from 0? In the Editor Inspector the default alpha for a color variable is sometimes set to 0.