Unity Script to Control 2D Outline Shader

PHOTO EMBED

Sat Mar 12 2022 12:04:00 GMT+0000 (Coordinated Universal Time)

Saved by @BryanJ22

using UnityEngine;

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

   [Range(0, 16)]
   public int outlineSize = 1;

   private SpriteRenderer spriteRenderer;

   private void Awake()
   {
      spriteRenderer = this.GetComponent<SpriteRenderer>();
   }

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

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

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

      float o = 0;
      if(outline)
      {
         o = 1f;
      }

      else
      {
         o = 0;
      }

      mpb.SetFloat("_Outline", o);
      mpb.SetColor("_OutlineColor", color);
      mpb.SetFloat("_OutlineSize", outlineSize);
      spriteRenderer.SetPropertyBlock(mpb);
   }
}
content_copyCOPY

Attach this script to any 2Dsprite that is using the 2D 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.