Search code examples
c#unity-game-enginegame-developmentparticle-system

Unity2D Particle System - Randomising Layer or Z transform value for appearing in front/behind/same layer as other game objects


I'm currently working on my weather system for a 2D Unity game project. What I am trying to accomplish is randomising which layer a particle will spawn on, so that sometimes it will appear behind other sprites such as the player or buildings, sometimes in front, and sometimes collide with them (on the same layer).

I'm relatively new to the particle system in general but after much playing around have accomplished my goals apart from this one.

I basically want to be able to randomise each particle to have, for instance, a Z value of -1, 0 or 1, with the player/other objects potentially being on 0, where the particles will collide with them. To visualise, here is the behaviour I currently have, where every particle collides with the objects, when I want roughly 1/3 to: https://i.imgur.com/vplFcye.gifv

Perhaps rather than working with the Z positional values, I should perhaps be thinking more in terms of layers? Randomising the layer the particles spawn on and therefore what the they can interact with, but either way I cannot find a way to script or set within the inspector the ability to change this layer/z value.

I have considered using three particle systems, which I believe would accomplish my goals, but is not ideal, and potentially detrimental to performance I'd assume?

If anyone has any insight, perhaps I've just missed a really obvious variable/setting in the inspector even.

Thanks.


Solution

  • Perhaps not the most elegant solve for this, but you could set your Emission shape to Mesh, Type to Edge, and use a custom mesh that's 3 separate rectangles, one each for the front/back/middle layer. I tested this and it seems to work well:

    Three Edge System

    The only issue I had with this is I originally tried this with a model that was just 3 edges, but found that the Unity importer strips edges not attached to faces, so I had to make them three near-zero-width faces in my mesh instead.