- Home /
Firing a particle effect prefab from your character
Hello everyone,
Have had some trouble coming up with the best ways to fire a particle effect prefab from the character in a first person view. Have googled around and most answers come in javascript where I am currently using C# (wanting a change from UnrealScript since switching to Unity).
Have documentation open and have been reading, thought I'd ask the awesome community here for some simple advice on what would the best way to do this be? Seeing a lot of different answers all around.
Cheers.
Answer by iwaldrop · Jun 08, 2013 at 01:40 AM
The simplest way would be to have a reference transform at the point where you want to spawn the particle effect. Ideally you have a spawn pool to work from that will cache n number of particle prefabs, but to get started you can simply have a GameObject member variable to hold a reference to the prefab that you'll be spawning. Once the setup is complete just instantiate the prefab at the position. You'll probably want a projectile type script on the prefab you're spawning that will drive your projectile, but you could also drive it from the 'gun'.
void OnFireGun()
{
GameObject projectile = GameObject.Instantiate(projectilePrefab, spawnRef.position, spawnRef.rotation) as GameObject;
}
// on the projectile
[RequireComponent(typeof(Rigidbody))]
public class Projectile : Monobehaviour
...
void OnAwake()
{
Rigidbody r = rigidbody;
if (r != null)
r.AddForce(transform.forward * speed, ForceMode.Impulse)
}
// OR, for rocket type projectiles that continually accelerate
// cache a reference to the rigidbody in OnAwake
Rigidbody r;
void FixedUpdate()
{
r.AddForce(transform.forward * speed, ForceMode.Acceleration)
}
Ask 10 people get 10 different answers as to the 'best' way. Experiment with what you find and you will soon discover a 'best' way of your own. It all depends on what your use case is. Welcome to Unity!
Thank you, that definitely clears my head up a bit and can now comfortably continue and add everything I wanted to.
Cheers!
Your answer
Follow this Question
Related Questions
Can a Particle System Use Custom Objects/Prefabs as Particles? 1 Answer
Is it possible to use Prefabs in the Particle emitter instead of meshes or billboards 1 Answer
Play after collision a Particle-prefab and spawn a new Coin-Prefab 1 Answer
how to rotate particles in a particle system 1 Answer
Move Particles 1 Answer