0
\$\begingroup\$

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?

\$\endgroup\$

2 Answers 2

5
\$\begingroup\$

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 ();
\$\endgroup\$
3
  • 1
    \$\begingroup\$ 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(); ... } \$\endgroup\$
    – DMGregory
    Jul 27, 2016 at 15:28
  • \$\begingroup\$ @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? \$\endgroup\$
    – BonnieB
    Jul 28, 2016 at 7:08
  • 2
    \$\begingroup\$ 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. \$\endgroup\$
    – DMGregory
    Jul 28, 2016 at 15:28
1
\$\begingroup\$

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> ();
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .