# How to instantiate a prefab only when something is hit, and for some seconds?

How do I instantiate a prefab only when something is hit for a few seconds? I mean, I just need to activate the particle system when something is hit. Now it always runs, even before I hit something. I need it to activate the particle system when something is hit and for 2-3 seconds.

This is what I do now:

public void Shot()
{
Destroy(gameObject);
Instantiate(effect, transform.position, transform.rotation);
}

• You mention the particle system running before you hit something. Without more detail, we can only speculate. However, I would suggest looking at your scene objects and endure that the particle system is not present prior to starting the game. If the particle system object is present when you start the game, it will automatically play itself, which may be the problem you are describing. I would create a prefab of this particle system and hold a reference to it and ensure it is not already present in your scene when you start the game. Best of luck – Savlon May 4 '17 at 21:40

As far as only triggering something when it's "hit", this is usually done via a Collider which triggers a callback when it hits something else, such as OnCollisionEnter https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnCollisionEnter.html

For destroying after a 2-3 second delay I would add a new script to the "effect" prefab that destroys itself after waiting some time:

public class DestroyAfterDelay : MonoBehaviour {
public float delay;

IEnumerator Start() {
yield return new WaitForSeconds( delay );
GameObject.Destroy( gameObject );
}
}


Heya :) this is pretty simple, the two ways I like to delay something is either using a coroutine or invoking a method. As for on hit if you want the particles to hit on the body where a bullet hits a person, Raycasting a shot and getting its hit.point will help you with achieving the position of the hit, if it is that u just want the particles to Emmitt at a transform, what u have is fine. As for code: Bare with me im on my phone :p

GameObject yourParticleSystem;

void OnCollisionEnter(Collision col)
{
//this is for if a bullet hits the player
if(col.gameObject.tag == "Bullet")
{
StartCoroutine(waitTime(3f));
}
}

IEnumerator waitTime (float time)
{
yield return new waitForSeconds (time);
Instantiate(yourParticleSystem, transform.position, Quaternio.identity);
//if u dont have play on awake ticked in particles a simple
yourParticleSystem.Play(); //will make it play
}


Because you aren't pooling your particles, you don't want to have multiple particle GameObject within the scene, if suggest either pooling ur particles or simple adding a destroy script on your particleSystem Eg:

void Start ()
{
Destroy(gameObject, 4f) // 4f is just a guess to how long the particles play for
}


Sorry if there are some syntax errors I tried my best on the phone hehe ^.^ hope u understand and it works :)))))