Skip to content

Instantly share code, notes, and snippets.

@randalfien
Created March 1, 2020 14:50
Show Gist options
  • Save randalfien/7a889c63520dfaf5fd18b01c11ee7a5d to your computer and use it in GitHub Desktop.
Save randalfien/7a889c63520dfaf5fd18b01c11ee7a5d to your computer and use it in GitHub Desktop.
Unity tool to replace a sprite across all scenes
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEditor.SceneManagement;
using UnityEngine.SceneManagement;
/**
* Use this utility to replace one sprite with another across all scenes.
* This can be easily extended for other types as well (AudioClip, Material, etc...)
*/
public class ReplaceSpriteWindow : EditorWindow
{
private static Sprite _target1;
private static Sprite _newTarget;
[MenuItem("Tools/Replace Sprite")]
static void Init()
{
var window = (ReplaceSpriteWindow) GetWindow(typeof(ReplaceSpriteWindow));
window.Show();
}
void OnGUI()
{
_target1 = EditorGUILayout.ObjectField("Replace This", _target1, typeof(Sprite), false) as Sprite;
_newTarget = EditorGUILayout.ObjectField("With this", _newTarget, typeof(Sprite), false) as Sprite;
if (_target1 != null && _newTarget != null)
if (GUILayout.Button("Replace"))
ReplaceSprites();
}
private static void ReplaceSprites()
{
EditorUtility.DisplayProgressBar("Replacing...", "", 0f);
var scenes = GetSavedScenes();
foreach (Scene scene in scenes) // iterate over all scenes in the project
{
bool change = false;
var rootObjects = scene.GetRootGameObjects();
foreach (GameObject rootObject in rootObjects)
{
var spriteRenderers = rootObject.GetComponentsInChildren<SpriteRenderer>(includeInactive:true);
foreach (var renderr in spriteRenderers)
{
if( renderr.sprite == _target1 )
{
renderr.sprite = _newTarget;
change = true;
Debug.Log("Replaced sprite in scene:" + scene.name + " obj:" + renderr.gameObject.name);
}
}
}
if (change)
{
EditorSceneManager.SaveScene(scene);
}
}
EditorUtility.ClearProgressBar();
}
private static IEnumerable<Scene> GetSavedScenes() {
string[] guids = AssetDatabase.FindAssets("t:Scene");
foreach (string guid in guids) {
yield return EditorSceneManager.OpenScene(AssetDatabase.GUIDToAssetPath(guid));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment