Skip to content

Instantly share code, notes, and snippets.

@minghanbai
Created January 3, 2017 05:49
Show Gist options
  • Select an option

  • Save minghanbai/56fdbab68db1095da61ce018ec3cd1e2 to your computer and use it in GitHub Desktop.

Select an option

Save minghanbai/56fdbab68db1095da61ce018ec3cd1e2 to your computer and use it in GitHub Desktop.

Revisions

  1. smallrice45 revised this gist Jan 3, 2017. No changes.
  2. smallrice45 created this gist Jan 3, 2017.
    73 changes: 73 additions & 0 deletions ParticelObjectPool
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,73 @@
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class ParticelObjectPool : MonoBehaviour {
    private ParticleSystem _ParticleSystem;
    private ParticleSystemRenderer _ParticleSystemRenderer;
    private ParticleSystem.Particle[] _Particles;
    public GameObject _ParticelObject;
    private GameObject _ObjectPool;
    int numParticlesAlive;
    void Start()
    {
    InitParticleSystem();
    InitObjectPool();

    }
    void InitParticleSystem()
    {
    _ParticleSystem = GetComponent<ParticleSystem>();
    _ParticleSystemRenderer = GetComponent<ParticleSystemRenderer>();

    _Particles = new ParticleSystem.Particle[_ParticleSystem.main.maxParticles];
    _ParticleSystemRenderer.renderMode = ParticleSystemRenderMode.None;
    }

    void InitObjectPool()
    {
    if (_ObjectPool == null)
    {
    _ObjectPool = new GameObject();
    _ObjectPool.name = "ParticelObjectPool_" + _ParticelObject.name;
    }
    for (int i = 0; i < _ParticleSystem.main.maxParticles; i++)
    {
    GameObject go = Instantiate(_ParticelObject);
    go.transform.SetParent(_ObjectPool.transform);
    }
    }

    void Update()
    {
    numParticlesAlive = _ParticleSystem.GetParticles(_Particles);

    // SetObjectPool
    for (int i = 0; i < _ObjectPool.transform.childCount; i++)
    {
    if (i < numParticlesAlive)
    {
    _ObjectPool.transform.GetChild(i).gameObject.SetActive(true);
    }
    else
    {
    _ObjectPool.transform.GetChild(i).gameObject.SetActive(false);
    }
    }

    // SetObjectTransform
    for (int i = 0; i < numParticlesAlive; i++)
    {
    if (_ParticleSystem.main.simulationSpace == ParticleSystemSimulationSpace.World)
    {
    _ObjectPool.transform.GetChild(i).transform.position = _Particles[i].position;
    }
    else
    {
    Debug.Log(_Particles[i].position);
    _ObjectPool.transform.GetChild(i).transform.position = transform.TransformPoint(_Particles[i].position);
    }
    _ObjectPool.transform.GetChild(i).eulerAngles = _Particles[i].angularVelocity3D + _ParticleSystem.transform.eulerAngles;
    }
    }
    }