Why does accessing ParticleSystem.IsAlive() raise this error?

I am trying to record if my particle system IsAlive with:

GameObject prefab = Instantiate (Prefab, myPosition, Quaternion.identity) as GameObject;

Component ps = prefab.GetComponent<ParticleSystem> ();
bool checkIfPSPlaying = ps.IsAlive ();
//bool playing = prefab.GetComponent<ParticleSystem> ().isPlaying // This works fine


The code above gives this error:

error CS1061: Type UnityEngine.Component does not contain a definition for IsAlive and no extension method IsAlive of type UnityEngine.Component could be found

What am I doing wrong?

It looks like you haven't set ps to the correct type (it should be a particle system). Try something like this:

GameObject prefab = Instantiate (Prefab, myPosition, Quaternion.identity) as GameObject;

ParticleSystem ps = prefab.GetComponent<ParticleSystem> ();
bool checkIfPSPlaying = ps.IsAlive ();

• If your code depends on the prefab having a particlesystem attached, it's helpful to show this in the type of the variable - that way the inspector will enforce this constraint at level creation time, rather than letting any errors slip through until runtime. eg... public ParticleSystem effectPrefab; void SpawnEffect() { ParticleSystem effect = Instantiate<ParticleSystem>(effectPrefab); effect.transform.position = myPosition; bool checkIfPlaying = effect.IsAlive(); ... }  – DMGregory Jul 27 '16 at 15:28
• @DMGregory, what you sounds important, but I don't quite understand... I should let effectPrefab know it belongs to *** myPrefab*** before I instantiate it (this is like a sanity check I guess?). But then when I assign effect, it points to an empty effectPrefab? – BonnieB Jul 28 '16 at 7:08
• I'm not sure if I understand your question, @BonnieB. In this example, you'd use effectPrefab to store the reference to your prefab, so you wouldn't have a separate myPrefab variable. When you instantiate effectPrefab, Unity spawns the whole object (not just the particle system part), and returns a reference to the instance's particle system. You don't have to do it this way, it's just a style choice that has some data validation benefits, and saves a separate GetComponent call. – DMGregory Jul 28 '16 at 15:28

When you assign an object to a variable with the type of its base class (like Component which is the base-class for all components, including ParticleSystem) you only get to call those methods which are defined in the base class.

When you want to call methods which are defined in a more specific class, you need to assign the object to a variable of that more specific type. Like this:

ParticleSystem ps = prefab.GetComponent<ParticleSystem> ();