Hello i was trying to make my particle effect which is the child of a parent object to activate whenever the parent collides with the ground.
My parent object is called “Player” and the particle object which is the child is called “Dust” and my ground has a tag named “Ground”. This code below is what ive written so far but it doesnt seem to work(its attached to “Player”)
private void OnCollisionEnter(Collider other)
{
if (other.CompareTag("Ground"))
{
gameObject.GetComponentInChildren<ParticleSystem>.isPlaying = true;
}
else
{
gameObject.GetComponentInChildren<ParticleSystem>.isPlaying = false;
}
I have been trying to find a solution online since im new to coding but i cant find anything helpfull
Hello and welcome to Unity answers!
I will try my best to explain how things should work and why in the most simple way.
First of all You should save a reference to the particle system you are using instead of getting that component each time you want to access it, it helps with performance in the future when you have a lot of scripts that search for components. for example:
private void OnCollisionEnter(Collider other)
{
//Saving the component for future use
ParticleSystem particles = GetComponentInChildren<ParticleSystem>();
//Here we check if we indeed find the Particle system and can use it
//or else we would get an error if we work with not existing component
if (particles != null)
{
if (other.CompareTag("Ground"))
{
particles.Play(); //Here we use the Play function to start the particle system
}
else
{
particles.Stop(); //Here we use the Stop function to stop the particle system from playing
}
}
}
Using particles.IsPlaying is for checking the state in which the particle system is at. (If it plays or not).
its not for controlling it.
Use particles.Play() or particles.Stop() to control it instead.
but even better is to make the particle system exposed in the inspector with [SerializeField] or Public
and then setting it there, It would be better than searching for it.