Awkward "if (!particle.isPlaying)... -> Solved with extension

Hey there,
just wanted to share a bit of code.
In this lecture we had many

if (!particleSuccess.isPlaying) particleSuccess.Play();

calls, and the same for all the stop calls… This didn’t look too nice in the code, so I made an extension class for the ParticleSystem, which solves this:

using UnityEngine;

namespace ProjectBoost
{
	public static class ParticleExtensions
	{
		public static void PlaySafe(this ParticleSystem sys) {
			if (!sys.isPlaying) sys.Play();
		}

		public static void StopSafe(this ParticleSystem sys) {
			if (sys.isPlaying) sys.Stop();
		}
	}
}

Just create a “ParticleExtensions.cs” file anywhere in your scripts folder and copy the code to it.
You then can safely start and stop particle systems without having to care whether they are currently playing or not, by using the PlaySafe() method:

// instead of
if (thrustMainParticles.isPlaying) thrustMainParticles.Stop();
// you can simply write
thrustMainParticles.StopSafe();

the extension does the “if…” for you

cheers
Mike

PS: same can be done with AudioSources

Thanks for posting this @Grisgram! I was wondering if you can point me in the direction of any C# documentation that explains exactly how this works? I’ve done some searching for extending classes in C# but the content always revolves around inheritance or doesn’t seem to describe your implementation.

Any additional information/links you can provide are greatly appreciated.
Thank you!

Hi, this is called an “Extension Method”

Basically, you can write an extension for any class by following these basic rules:

  • it is in a static class
  • it is a static method and the first argument has the keyword this, like in the example above. The type you enter after the “this” keyword is the class that will be extended.

hope this helps.

cheers, Mike

This is very helpful indeed, and exactly what I was looking for! Thanks Mike!

Privacy & Terms