top of page

DissolvingController.cs

using System.Collections;
using UnityEngine;
using UnityEngine.VFX;

#if ENABLE_INPUT_SYSTEM
using UnityEngine.InputSystem;
#endif

public class DissolvingController : MonoBehaviour
{
    [Header("Target Components")]
    public SkinnedMeshRenderer skinnedMesh;
    public VisualEffect vfxGraph;

    [Header("Dissolve Settings")]
    public float dissolveRate = 0.0125f;
    public float refreshRate = 0.025f;

    [Header("Hotkey Settings (Legacy Input)")]
    public KeyCode triggerHotkey = KeyCode.Space;

    private Material[] meshMaterials;
    private bool isDissolving = false;

    void Start()
    {
        if (skinnedMesh != null)
        {
            // Store materials from the renderer
            meshMaterials = skinnedMesh.materials;
        }
    }

    void Update()
    {
        bool inputTriggered = false;

#if ENABLE_INPUT_SYSTEM
        // Unity 6 New Input System check for Space key
        if (Keyboard.current != null && Keyboard.current.spaceKey.wasPressedThisFrame)
        {
            inputTriggered = true;
        }
#else
        // Legacy Input Manager check
        if (Input.GetKeyDown(triggerHotkey))
        {
            inputTriggered = true;
        }
#endif

        if (inputTriggered && !isDissolving)
        {
            StartCoroutine(DissolveCo());
        }
    }

    private IEnumerator DissolveCo()
    {
        isDissolving = true;

        // Play particle emission inside VFX Graph
        if (vfxGraph != null)
        {
            vfxGraph.Reinit(); // Clean state reset in Unity 6
            vfxGraph.Play();
        }

        if (meshMaterials != null && meshMaterials.Length > 0)
        {
            float counter = 0f;

            // Incrementally dissolve the materials over time
            while (meshMaterials[0].GetFloat("_DissolveAmount") < 1f)
            {
                counter += dissolveRate;

                for (int i = 0; i < meshMaterials.Length; i++)
                {
                    meshMaterials[i].SetFloat("_DissolveAmount", counter);
                }

                yield return new WaitForSeconds(refreshRate);
            }
        }

        isDissolving = false;
    }
}

bottom of page