Unity C# script that spawns Particles
Here’s a clean, production‑ready Unity C# script that spawns particle effects. It’s flexible, readable, and easy to drop into your existing 2D or 3D workflow.
🎇 Simple & Flexible Particle Spawner (Unity C#)
using UnityEngine;
public class ParticleSpawner : MonoBehaviour
{
[Header("Particle Settings")]
public ParticleSystem particlePrefab; // Assign your particle prefab here
public Transform spawnPoint; // Optional: where particles appear
public float spawnInterval = 1f; // Time between spawns
public bool autoSpawn = false; // Toggle automatic spawning
private float timer;
void Update()
{
if (!autoSpawn) return;
timer += Time.deltaTime;
if (timer >= spawnInterval)
{
SpawnParticles();
timer = 0f;
}
}
public void SpawnParticles()
{
if (particlePrefab == null)
{
Debug.LogWarning("ParticleSpawner: No particle prefab assigned.");
return;
}
// Determine spawn position
Vector3 pos = spawnPoint != null ? spawnPoint.position : transform.position;
// Instantiate particle system
ParticleSystem ps = Instantiate(particlePrefab, pos, Quaternion.identity);
// Optional: destroy after duration
Destroy(ps.gameObject, ps.main.duration + ps.main.startLifetime.constantMax);
}
}
🧩 How to Use It
1. Create a Particle Prefab
- In Unity, create a Particle System in your scene.
- Adjust it until it looks right.
- Drag it into your Project window to make it a prefab.
2. Add the Script
- Create a new C# script named
ParticleSpawner.cs. - Paste the code above.
- Attach it to any GameObject (e.g., an empty object called ParticleManager).
3. Assign References
- Drag your particle prefab into the Particle Prefab field.
- Optionally assign a Spawn Point transform.
- Toggle Auto Spawn if you want continuous spawning.
4. Manual Trigger (e.g., from a button or event)
You can call:
GetComponent<ParticleSpawner>().SpawnParticles();
⚡ Want variations?
I can generate versions for:
- Burst spawning
- Object pooling
- Spawning on collision
- Spawning based on mouse click
- Spawning with random offsets, colors, or velocities
Comments