Search code examples
unity-game-engineparticles

Unity disable particle system when outside of camera


I am making a 2D game in unity that has an underwater theme. To make it look really pretty, I use a script to spawn glowy objects at random locations in the map. These objects are blank sprites with Particle Systems attached to them.

The problem is, I have about 100 of them active in the map at a time, and though it looks really pretty, the game lags on computers that don't have an i5 processor or faster.

The solution I thought of was to disable the objects while they are out of camera bounds so there is only about 4 or 5 active at a time...

Here's my script:

void Update () {

    if (this.transform.position.x < Camera.main.transform.position.x + 13 && this.transform.position.x > Camera.main.transform.position.x - 13 && this.transform.position.y < Camera.main.transform.position.y + 13 && this.transform.position.y > Camera.main.transform.position.y - 13) {             this.gameObject.particleEmitter.emit = true;
        this.gameObject.particleSystem.Play ();


            } 

    else {

        this.gameObject.particleSystem.Pause ();


    }
} 

Ok, it checks if the object is outside the camera bounds correctly, but when it comes to disabling the object, I get this error:

"NullReferenceException: Object reference not set to an instance of an object"


Solution

  • You use both particleEmitter, which refers to the legacy particle system, and particleSystem, which refers to the new Souriken system. You're probably only using Souriken particles, so I would rewrite it like this:

    void Update ()
    {
        if (this.transform.position.x < Camera.main.transform.position.x + 13
            && this.transform.position.x > Camera.main.transform.position.x - 13
            && this.transform.position.y < Camera.main.transform.position.y + 13
            && this.transform.position.y > Camera.main.transform.position.y - 13)
        {
            particleSystem.Play ();
        } 
        else
        {
            particleSystem.Pause ();
        }
    }