4
votes

How can I properly play the particle system component, which is attached to a GameObject? I also attached the following script to my GameObject but the Particle System does not play. How do I fix this?

public Transform gameobject1;
public Transform gameobject2;
public ParticleSystem particules;

void Start()
{
    float distance = Vector3.Distance(gameobject1.position, gameobject2.position);
}

void Update()
{
    if(distance == 20)
  {
      particules.Play();
  }
}
2
@Micky Not in my case. I edited the question. - user5622430
Ah yes. Thanks Dimitri - Micky
@Micky I edited the question even more with details. - user5622430

2 Answers

2
votes

Assuming this is the exact code you wrote , You need to first use the GetComponentmethod to be able to perform actions on your particle system

Your code should look like this:

public Transform gameobject1;
public Transform gameobject2;
public ParticleSystem particules;
public float distance;

//We grab the particle system in the start function
void Start()
{
    particules = GetComponent<ParticleSystem>();
}

void Update()
{
    //You have to keep checking for the Distance
    //if you want the particle system to play the moment distance goes below 20 
    //so we set our distance variable in the Update function.
    distance = Vector3.Distance(gameobject1.position, gameobject2.position);

    //if the objects are getting far from each other , use (distance >= 20)
    if(distance <= 20) 
    {
        particules.Play();
    }
}
0
votes

I don't see you declaring distance in your class, but you use it under update. Declare distance as a private float with your other members and just define it in start.

Assuming that your code isn't exactly like that, your also issue looks like it stems from using a solid value with distance. Try using less than or equal to 20.

if(distance <= 20)

Or you could try greater than 19 and less than 21.

if(distance <= 21 && distance >= 19)