following this course we have created separate Particle Systems for crashing and for skiing for the player. We do call them by using Serialize Field in the script and then drag and dropping those Particle Systems to those fields. But how should the script look like if we would want to just select the proper Particle System directly in the script?
For example instead of this:
[SerializeField] ParticleSystem dusttrailEffect;
how would it look like to call (play/stop) directly the effect (called in my case DustTrail Effect)?
Thank you
Ladislav
public class DustTrail : MonoBehaviour
{
[SerializeField] ParticleSystem dusttrailEffect;
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == “Ground”)
{
dusttrailEffect.Play();
}
}
void OnCollisionExit2D(Collision2D collision)
{
if (collision.gameObject.tag == “Ground”)
{
dusttrailEffect.Stop();
}
}
}
I have tried changing the beginning of script to this:
// [SerializeField] ParticleSystem dusttrailEffect;
ParticleSystem system
{
get
{
if (dusttrailEffect == null)
dusttrailEffect = GameObject.Find("DustTrail Effect").GetComponent<ParticleSystem>();
return dusttrailEffect;
}
}
ParticleSystem dusttrailEffect;
But I just get an error when plaing
NullReferenceException: Object reference not set to an instance of an object
DustTrail.OnCollisionEnter2D (UnityEngine.Collision2D collision) (at Assets/Scripts/DustTrail.cs:23)
It’s great to see that you are challenging yourself. Unfortunately, the code is not formatted, so it is a bit difficult to read. I just focussed on your last code and formatted it for you.
I understood your goal was to find ParticleSystem components on specific game objects via code. If I understood that correctly, your solution is how one would do that. Since components do not have any name, there is no other way to find something that does have a name, then look for the ParticleSystem.
If the DustTrail methods get executed multiple times during runtime, I would recommend to cache the reference to the ParticleSystems you found because the Find* methods in Unity are very slow and resource-intensive.