Unity script to control 3D outline shader

PHOTO EMBED

Sat Mar 12 2022 12:38:14 GMT+0000 (Coordinated Universal Time)

Saved by @BryanJ22

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[ExecuteInEditMode]
public class ToonOutline : MonoBehaviour
{
   public Color color = Color.black;

   [Range(0, 3)]
   public float outlineSize = 1f;

   private MeshRenderer meshRenderer;

   private void Awake()
   {
      meshRenderer = this.GetComponent<MeshRenderer>();
   }

   private void OnEnable()
   {
      updateOutline(true);
   }

   private void OnDisable()
   {
      updateOutline(false);
   }

   void updateOutline(bool outline)
   {
      MaterialPropertyBlock mpb = new MaterialPropertyBlock();
      meshRenderer.GetPropertyBlock(mpb);

      float size = 0;
      if (outline)
      {
         size = outlineSize;
      }

      else
      {
         size = 0;
      }

      mpb.SetColor("_OutlineColor", color);
      mpb.SetFloat("_OutlineSize", size);
      meshRenderer.SetPropertyBlock(mpb);
   }
}
content_copyCOPY

Attach this script to any 3D object that is using the Outline shader. When the script is enabled, outlines will be used in the shader, but when the script is disabled or not present, the outlines will not be used in the shader.