- Home /
Instantiate particle effect for the player
Hi,
What I have done so far is created a "particle system" under GameObject->Create Other and added it to my scene. I can now see 1 group of particles emitting.
So we want to create a new folder called "Resources" under assets in my project directory and within it, create an empty prefab. We can call this empty prefab, "ParticlePrefab".
I go to my heirarchy select the Particle System (default naming convention) and drag it to my ParticlePrefab, which changes it from a whitish color, to a bluish color.
I go to my player C# script, add the statement:
public GameObject ParticlePrefab;
I go to my player (game object) and drag the ParticlePrefab onto the ParticlePrefab slot, so that my Player is aware of the particle system.
So now I want to Instantiate the ParticlePrefab when I press a key, But I can already see it happening off to the side in the scene.
Maybe, with this code someone can help see why: using UnityEngine; using System.Collections;
public class Player : MonoBehaviour {
public GameObject ParticlePrefab;
void Start() { // Intialize game start code }
void Update() { // Move Player code }
void OnTriggerStay(Collider other) {
if (Input.GetKeyDown("h"))
{ Instantiate(ParticlePrefab); } // ... } }
I am not getting a Null reference error for the prefab, "ParticlePrefab"
Answer by Mike 3 · May 27, 2010 at 02:38 AM
Is the one from the scene (which you made the prefab from) still there?
If so, remove it
Edit:
using UnityEngine; using System.Collections;
public class Player : MonoBehaviour {
public GameObject ParticlePrefab; private GameObject instantiated; private Vector3 lastPos;
void Start() { // Intialize game start code }
void Update() { // Move Player code if(Vector3.Distance(lastPos, transform.position) > 0.01f) { lastPos = transform.position; if (instantiated != null) Destroy(instantiated); } }
void OnTriggerStay(Collider other) {
if (Input.GetKeyDown("h")) //one at a time { instantiated = (GameObject)Instantiate(ParticlePrefab, transform.position, transform.rotation); } // ... } }
Alrighty, so I think that what you suggested works. However, what I am going for is that the player needs to be able to emit particles from its center of mass when the user presses "h"
Instantiate(ParticlePrefab, transform.position, transform.rotation);
How to I destroy the ParticlePreFab? Destroy(ParticlePrefab) gives me errors.
You need to store a reference to it when you create it, will edit my answer to reflect that
Your answer
Follow this Question
Related Questions
Getting a button to run a function 2 Answers
WWW.CheckSecurityOnHeaders throwing NullReferenceException 1 Answer
NullReferenceException? 2 Answers
Null Reference Expantion 1 Answer