- Home /
How to move particles from script ?
Im trying to move all particles to a spot. I wrote a script,but it doesnt work.
for(int i = 0; i < particleEmitter.particles.Length;i++)
{
particleEmitter.particles[i].position = Vector3.MoveTowards(particleEmitter.particles[i].position,spot.transform.position,Time.deltaTime * speed);
}
Answer by CHPedersen · Aug 05, 2013 at 01:05 PM
It's because your script isn't reassigning the particle array back to the emitter. Notice that ParticleEmitter.particles is a property, not a public variable. This indicates it's implemented as a set of getter/setter methods. The get method, which is called when you access the property, actually returns a deep-copy of the actual array. This behavior is similar to how eg. the vertices array of the Mesh class works. You can then make changes to this copy as you see fit, but they will not take effect until you assign the copy back to the emitter:
// Extract copy
Particle[] particles = particleEmitter.particles;
// Do changes
for (int i = 0; i < particles.Length; i++)
{
particles[i].position = Vector3.MoveTowards(particleEmitter.particles[i].position, spot.transform.position, Time.deltaTime * speed);
}
// Reassign back to emitter
particleEmitter.particles = particles;
Beware, for the record, that modifying particles in this manner can be very inefficient when there are thousands of particles. Be especially careful about calling list properties in loop conditions the way you did in your original code. Since the property returns a full copy of the entire particle array every time you call particleEmitter.particles, it means you're assigning a new array of all particles every time the loop iterates, because it accesses the particles-property to check the length on every iteration. This would create a massive memory overhead. I've circumvented that by storing the copy once outside the loop (at the line commented "Extract copy").
Answer by ryisnelly · Aug 05, 2013 at 01:01 PM
cant you use unitys built in particle system? Components>Effects>Particle System
thats what he is doing, however it does not have the needed functionality to get the expected behaviour
i myself need to code in patterns for each particle and this is pretty much the only way to do it that i have found.
Answer by mavin_197 · Oct 18, 2018 at 11:20 AM
And you need to SetParticles
int count = this.particleSys.GetParticles(this.particles); this.particleSys.SetParticles(this.particles, count);
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
Still trying to move walls 1 Answer