How do I change the trail renderer color in script?
If you are using only two colors in your trail you can use a much simpler method.
Use those two functions for the renderer to set the starting and ending color in your gradient.
You can use one of the basic colors like in the 1st line of the code below, or assign your custom color based on the RGB values.
myTailRenderer.startColor = Color.white;
myTailRenderer.endColor = new Color (0.35f, 1f, 0.75f);
Works like a charm. Changing the whole gradient I find a bit too much work.
Docs:
TrailRenderer.startColor
The first thing you need to do is create a material, and add it to your Trail Renderer. Then you have two options to change the Color via script.
-
Change the Color via the new
material you just created. -
Change the color by changing the
Gradient. (2018 only).
If you do not need a Gradient I’d recommend just changing the Material color as it’s a straightforward solution. To do this we’ll assume the Trail Renderer is on the same Game Object as the MonoBehaviour script you are working in, then you can simply do something like this:
TrailRenderer myTrailRenderer = GetComponent<TrailRenderer>();
myTrailRenderer.material.color = myColor;
For reference take a look at the Trail Renderer, Material.color, and Gradient documentation.