Unity 2017.3中如何获取粒子随机渐变颜色?
Hey there! I’ve run into this exact issue back in the Unity 2017.x days—getting the actual random gradient color of spawned particles can be tricky because the default property access doesn’t always expose the computed color. Let’s break down how to fix this:
1. Get the Actual Color of Spawned Particles
The key here is to use the ParticleSystem.GetParticles() method to retrieve the live particle data, which includes the final random color chosen from your gradient. Here’s a code example:
using UnityEngine; public class ParticleColorLogger : MonoBehaviour { private ParticleSystem _particleSystem; void Start() { _particleSystem = GetComponent<ParticleSystem>(); } void Update() { // Only run if there are active particles if (_particleSystem.particleCount == 0) return; // Initialize an array to hold particle data ParticleSystem.Particle[] particles = new ParticleSystem.Particle[_particleSystem.particleCount]; int particleCount = _particleSystem.GetParticles(particles); // Loop through each particle to get its color for (int i = 0; i < particleCount; i++) { Color particleColor = particles[i].startColor; Debug.Log($"Particle {i} color: {particleColor}"); } } }
Important Notes:
- Run in Play Mode: This only works when the particle system is actively spawning particles in Play Mode—you won’t get valid data in Edit Mode.
- Check Particle Modules: If you’re using modules like
Color Over LifetimeorColor By Speed, the particle’s final color will be a combination ofstartColorand those module values. To get the final rendered color, you’d need to compute that manually using the module settings.
2. Generate a Random Color from the Gradient (Before Spawning)
If you need to get a random color from your gradient before spawning a particle (e.g., to sync another object’s color), you can directly evaluate the gradient:
MinMaxGradient particleGradient = _particleSystem.main.startColor; Color randomGradientColor = particleGradient.Evaluate(Random.value); // Use this color for other purposes, or pass it to manual emission _particleSystem.Emit(1, Vector3.zero, Vector3.zero, randomGradientColor, 1.0f);
This works because MinMaxGradient.Evaluate() will pick a random color from your defined gradient range, matching what the particle system uses when spawning particles automatically.
Why You Were Getting Black
In Unity 2017.3, accessing _particleSystem.main.startColor.color directly returns the base color (which might be black if you’re using a gradient instead of a solid color), not the randomly selected gradient color. The GetParticles() method is the only way to retrieve the actual color assigned to each spawned particle.
内容的提问来源于stack exchange,提问作者Absinthe

