首页 > 解决方案 > Unity .GetParticles() 高 CPU 峰值

问题描述

我在粒子系统上使用 .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);
    }
}

脚本

标签: unity3d

解决方案


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


推荐阅读