SHA256
39 lines
1.7 KiB
C#
39 lines
1.7 KiB
C#
using System;
|
|
using System.Runtime.CompilerServices;
|
|
using UnityEngine;
|
|
|
|
namespace ADOFAIRenderer.Util
|
|
{
|
|
/// <summary>Particle system helpers.</summary>
|
|
internal static class ParticleUtil
|
|
{
|
|
/// <summary>
|
|
/// Renderer found for each particle system. Weak keys: an entry is dropped when its ParticleSystem object is collected.
|
|
/// Main thread.
|
|
/// </summary>
|
|
private static readonly ConditionalWeakTable<ParticleSystem, ParticleSystemRenderer> Cache = new();
|
|
|
|
/// <summary>
|
|
/// Returns the ParticleSystemRenderer that belongs to <paramref name="ps"/>. When a GameObject has several particle
|
|
/// systems and renderers, the renderer with the same component index as the particle system is used; otherwise the
|
|
/// first renderer of the GameObject. The result is cached per particle system. Main thread.
|
|
/// </summary>
|
|
/// <param name="ps">Particle system; null or destroyed returns null.</param>
|
|
/// <returns>The renderer, or null when the GameObject has none.</returns>
|
|
public static ParticleSystemRenderer? GetRenderer(this ParticleSystem ps)
|
|
{
|
|
if (!ps) return null;
|
|
if (Cache.TryGetValue(ps, out var renderer) && renderer) return renderer;
|
|
|
|
var particleSystems = ps.GetComponents<ParticleSystem>();
|
|
var renderers = ps.GetComponents<ParticleSystemRenderer>();
|
|
var index = Array.IndexOf(particleSystems, ps);
|
|
|
|
renderer = index >= 0 && index < renderers.Length ? renderers[index] : ps.GetComponent<ParticleSystemRenderer>();
|
|
if (renderer) Cache.Add(ps, renderer);
|
|
|
|
return renderer;
|
|
}
|
|
}
|
|
}
|