Unity .GetParticles()高CPU峰值

时间:2018-07-10 00:49:57

标签: unity3d

我在粒子系统上使用.GetParticles()来破坏超出特定范围的粒子。我的脚本在下面,粒子系统变量被缓存。我附上了占用CPU的详细资料,它指向GetParticles()。我找不到任何文档说明为什么这种方法不好,因为该脚本仅附加到一个游戏对象上。

感谢任何见识,谢谢!

private void Update()
{if (Time.time > (delayTimer + 0.02f))
    {
        delayTimer = Time.time;
        transform.position = new Vector3(transform.position.x, Water.transform.position.y - 2f, transform.position.z);

        //Gets the change in the waters height and resets it 
        var waterHeightChange = Mathf.Abs(Water.transform.position.y - waterHeight);
        waterHeight = Water.transform.position.y;

        //Gets the distance to the top of the water to pop the bubble if surpassed 
        var DistanceToDestroy = Mathf.Abs((Water.transform.position.y + (Water.transform.localScale.y / 2f) - .15f) - transform.position.y);

        //Creates a particle array sized a the emitters maximum particles
        //Gets the particles from the emitter system and transfers into array of particles, returns total number of particles
        //Only called on occasion (once at start really) to make allocation as minimal as possible
        if (pSystemParticles == null || pSystemParticles.Length < pSystem.main.maxParticles)
        {
            pSystemParticles = new ParticleSystem.Particle[pSystem.main.maxParticles];

        }

        int numParticlesAlive = pSystem.GetParticles(pSystemParticles);

        for (int i = 0; i < numParticlesAlive; i++)
        {

            //Changes the height accordingly for each particle
            newPos.Set(pSystemParticles[i].position.x, pSystemParticles[i].position.y, pSystemParticles[i].position.z + waterHeightChange);
            //Grab the 'y' positional height relative to the emitter
            var particleHeight = newPos.z;

            if (particleHeight >= DistanceToDestroy)
            {

                //Deletes particle if needed
                pSystemParticles[i].remainingLifetime = 0;
            }
        }
        //Sets the particle system from the modified array
        pSystem.SetParticles(pSystemParticles, numParticlesAlive);
    }
}

Script

1 个答案:

答案 0 :(得分:1)

我不确定为什么会出现这种峰值,但这似乎超出了您的控制范围。也许您可以使用Collision Module,在水线上方放置一个不可见的平面,使粒子停止在该平面上,然后设置碰撞模块,以使粒子在碰撞时失去整个寿命(寿命损失= 1)。这样,它们在与飞机相撞时应该消失了。之所以会更快,是因为粒子永远不必进入C#世界,而且编写的代码要少得多。