Skip to content

Instantly share code, notes, and snippets.

@wakeup5
Last active January 30, 2020 05:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wakeup5/f75b7e64e48ff6b00d2fdd023080e73c to your computer and use it in GitHub Desktop.
Save wakeup5/f75b7e64e48ff6b00d2fdd023080e73c to your computer and use it in GitHub Desktop.
SpriteSwitcher is a component that lets you easily change textures in sprite swap based animations in Unity3D.
using Sirenix.OdinInspector;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
[ExecuteInEditMode]
public class SpriteSwitcher : MonoBehaviour
{
[HideInInspector]
[SerializeField]
private Sprite sprite;
#if UNITY_EDITOR
[SerializeField]
private Texture texture;
private Texture prevTexture;
private void OnValidate()
{
if (prevTexture != texture)
{
prevTexture = texture;
if (texture == null)
{
switchSprites = new Sprite[0];
return;
}
string path = UnityEditor.AssetDatabase.GetAssetPath(texture);
Object[] assets = UnityEditor.AssetDatabase.LoadAllAssetsAtPath(path);
switchSprites = assets.Where(o => o is Sprite).Select(o => o as Sprite).ToArray();
GetComponent<SpriteRenderer>().sprite = switchSprites[0];
}
}
#endif
[HideInInspector]
[SerializeField]
private Sprite[] switchSprites;
private SpriteRenderer spriteRenderer;
private void Awake()
{
spriteRenderer = GetComponent<SpriteRenderer>();
}
private void LateUpdate()
{
if (spriteRenderer.sprite.name != sprite.name)
{
for (int i = 0; i < switchSprites.Length; i++)
{
if (sprite.name == switchSprites[i].name)
{
spriteRenderer.sprite = switchSprites[i];
break;
}
}
}
}
}

SpriteSwitcher is a component that lets you easily change textures in sprite swap based animations.
Imgur

You need to change the animation to replace SpriteSwitcher.sprite instead of SpriteRenderer.sprite.
Imgur

Frames are identified by the name of the sprite, so each texture sprite must have the same name. Imgur

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment