- Home /
Play ParticleSystem on RayCastHit Object
I have a GameObject with a Particle System component on it (this is an enemy).
I have attached a blood Particle Effect to enemy so when I hit the enemy, the blood will show.
How can I play the Particle System on an object I hit with RayCastHit?
I have tried everything I can think of over the past hour or 2, no luck:
if(Physics.Linecast(playertarget.transform.position, attackrange.transform.position, out hit)){
if(hit.transform){
hit.transform.particleSystem.Play();
You don't have to check for a transform. If the LineCast() hits something, then a transform will exist. So now you need to debug.
Debug.DrawLine(playertarget.transform.position, attackrange.transform.position);
if(Physics.Linecast(playertarget.transform.position, attackrange.transform.position, out hit)) {
Debug.Log(hit.collider.name + ", " + hit.collider.tag);
hit.transform.particleSystem.Play();
}
Thanks, I removed that check. Logging the collider shows I have hit the correct object. But calling hit.transform.particleSystem.Play(); causes a: NullReferenceException: Object reference not set to an instance of an object
I think maybe because the Particle GameObject is a child, so I try to call: GameObject b = hit.transform.Find("Blood"); But then this causes a: error CS0029: Cannot implicitly convert type UnityEngine.Transform' to
UnityEngine.GameObject'
Transform inherits 'particleSystem', so you can do (if you are absolutely sure the object hit has a 'Blood' immediate child):
hit.transform.Find("Blood").particleSystem.Play();
You should probably be checking the tag or name in the hit before executing this code (to avoid a null reference exception).
$$anonymous$$y guess is that "Blood" is not an immediate child, so you need to specify a path in the Transform.Find(). See the reference. As an alternate, you can try (C#):
hit.transform.GetComponentInChildren<ParticleSystem>().Play();
...or Javascript:
hit.transform.GetComponentInChildren(ParticleSystem).Play();
This assumes that there is only one ParticleSystem in the object's children.
Got it working, thanks a ton robertbu! hit.transform.Find("Blood").particleSystem.Play(); works great and I added some error checking as well.
Answer by Selzier · Oct 01, 2014 at 05:20 AM
Thanks robertbu for the help.
I ended up going with this:
if (hit.transform.Find("Blood")){
hit.transform.Find("Blood").particleSystem.Play();
}
Your answer
Follow this Question
Related Questions
Using a ray to make drop script 1 Answer
See what object I hit in raycast 0 Answers
How do I ask if RaycastHit returns null? 3 Answers
Grabbing MonoBehavior object from collision 1 Answer
Some GameObjects can't touch !!! 0 Answers