Unity Editor Script
A Unity Editor script that automatically checks for untracked asset references during save, scene, and prefab updates, with an option to manually trigger the check via menu.Anonymous
C#
09/03/2025 9:21 AM
3.4 KB
26
Indexable
Never
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;
[InitializeOnLoad]
public static class GitReferenceCheckerAuto
{
static GitReferenceCheckerAuto()
{
// Hook into save & domain reload
EditorApplication.delayCall += RunCheck;
EditorSceneManager.sceneSaved += (scene) => RunCheck();
PrefabUtility.prefabInstanceUpdated += (go) => RunCheck();
}
[MenuItem("Tools/Git/Check References (Deep)")]
public static void RunCheck()
{
if (!CheckStagedReferences(out var untracked))
{
Debug.LogWarning("⚠️ Found references to untracked assets:\n" +
string.Join("\n", untracked));
}
else
{
Debug.Log("✅ All staged scene/prefab references are tracked.");
}
}
static bool CheckStagedReferences(out List<string> untrackedReferences)
{
untrackedReferences = new List<string>();
try
{
var stagedFiles = RunGit("diff --cached --name-only")
.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries)
.Where(f => f.EndsWith(".unity") || f.EndsWith(".prefab"))
.ToList();
if (stagedFiles.Count == 0)
return true;
var referencedGuids = new HashSet<string>();
foreach (var file in stagedFiles)
{
string assetPath = file.Replace("\\", "/");
var deps = AssetDatabase.GetDependencies(assetPath, true);
foreach (var dep in deps)
{
var guid = AssetDatabase.AssetPathToGUID(dep);
if (!string.IsNullOrEmpty(guid))
referencedGuids.Add(guid);
}
}
foreach (var guid in referencedGuids)
{
var path = AssetDatabase.GUIDToAssetPath(guid);
if (string.IsNullOrEmpty(path))
continue;
if (!IsTrackedByGit(path))
untrackedReferences.Add(path);
}
return untrackedReferences.Count == 0;
}
catch (Exception ex)
{
Debug.LogError("GitReferenceChecker error: " + ex);
return false;
}
}
static string RunGit(string arguments)
{
var psi = new ProcessStartInfo("git", arguments)
{
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};
using (var p = Process.Start(psi))
{
string stdout = p.StandardOutput.ReadToEnd();
string stderr = p.StandardError.ReadToEnd();
p.WaitForExit();
if (p.ExitCode != 0)
throw new Exception($"git {arguments} failed: {stderr}");
return stdout;
}
}
static bool IsTrackedByGit(string path)
{
path = path.Replace("\\", "/");
try
{
var result = RunGit($"ls-files --error-unmatch \"{path}\"");
return !string.IsNullOrEmpty(result);
}
catch
{
return false;
}
}
}
Editor is loading...
Leave a Comment