ParticleEffectForUGUI/Samples~/Cartoon FX & War FX Demo/CFX_Demo_With_UIParticle.cs

88 lines
2.8 KiB
C#
Raw Normal View History

using System;
using System.Linq;
using System.Reflection;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using Object = UnityEngine.Object;
2023-08-17 08:43:02 +08:00
namespace Coffee.UIExtensions.Demo
{
2023-08-17 08:43:02 +08:00
public class CFX_Demo_With_UIParticle : MonoBehaviour
{
2023-08-17 08:43:02 +08:00
private MonoBehaviour _demo;
private Toggle _spawnOnUI;
private UIParticle _uiParticle;
2023-08-17 08:43:02 +08:00
// Start is called before the first frame update
private void Start()
{
_uiParticle = GetComponentInChildren<UIParticle>();
_spawnOnUI = GetComponentInChildren<Toggle>();
_demo = FindObjectOfType("CFX_Demo_New") as MonoBehaviour
?? FindObjectOfType("WFX_Demo_New") as MonoBehaviour;
2023-08-17 08:43:02 +08:00
SetCanvasWidth(800);
SetCanvasRenderOverlay(true);
}
2023-08-17 08:43:02 +08:00
// Update is called once per frame
private void Update()
{
if (!_spawnOnUI.isOn || !_demo || !Input.GetMouseButtonDown(0)) return;
2023-08-17 08:43:02 +08:00
foreach (Transform child in _uiParticle.transform)
{
Destroy(child.gameObject);
}
2023-08-17 08:43:02 +08:00
var particle = _demo.GetType()
.GetMethod("spawnParticle", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)
?.Invoke(_demo, Array.Empty<object>()) as GameObject;
if (!particle) return;
2023-08-17 08:43:02 +08:00
particle.transform.localScale = Vector3.one;
_uiParticle.SetParticleSystemInstance(particle);
}
2023-08-17 08:43:02 +08:00
private static Object FindObjectOfType(string typeName)
{
var type = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(x => x.GetTypes())
.FirstOrDefault(x => x.Name == typeName);
2023-08-17 08:43:02 +08:00
return type == null ? null : FindObjectOfType(type);
}
2023-08-17 08:43:02 +08:00
public void SetCanvasWidth(int width)
{
2023-08-17 08:43:02 +08:00
var scaler = GetComponentInParent<CanvasScaler>();
scaler.screenMatchMode = CanvasScaler.ScreenMatchMode.MatchWidthOrHeight;
scaler.matchWidthOrHeight = 0;
var resolution = scaler.referenceResolution;
resolution.x = width;
scaler.referenceResolution = resolution;
}
2023-08-17 08:43:02 +08:00
public void SetCanvasRenderOverlay(bool enable)
{
2023-08-17 08:43:02 +08:00
var canvas = GetComponentInParent<Canvas>();
if (enable)
{
canvas.renderMode = RenderMode.ScreenSpaceOverlay;
}
else
{
canvas.worldCamera = Camera.main;
canvas.renderMode = RenderMode.ScreenSpaceCamera;
canvas.planeDistance = 5;
}
}
2023-08-17 08:43:02 +08:00
public void LoadScene(string scene)
{
SceneManager.LoadScene(scene);
}
}
}