Skip to content

Instantly share code, notes, and snippets.

@mrtrizer
Created December 15, 2022 03:41
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 mrtrizer/60aeaf207719efaac8bd27602fffaeca to your computer and use it in GitHub Desktop.
Save mrtrizer/60aeaf207719efaac8bd27602fffaeca to your computer and use it in GitHub Desktop.
Fix fileId in asset file. May be useful if you change type of field and Unity doesn't fix references. Make sure to change regex pattern for your needs.
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Text.RegularExpressions;
public class ReferenceFixTool
{
[MenuItem("CONTEXT/ScriptableObject/Fix References")]
static void FixReferences(MenuCommand command)
{
ScriptableObject obj = command.context as ScriptableObject;
Debug.Log($"Fixing references for {obj.name}");
var contextAssetPath = AssetDatabase.GetAssetPath(obj);
Debug.Log($"Open scriptable object at path: {contextAssetPath}");
var inputStringStream = new StreamReader(contextAssetPath);
var outputStringStream = new StringWriter();
while (!inputStringStream.EndOfStream)
{
var line = inputStringStream.ReadLine();
var match = Regex.Match(line, @"prefabRef: \{fileID: ([-0-9]*), guid: ([a-z0-9]*)");
if (match.Success)
{
var assetPath = AssetDatabase.GUIDToAssetPath(match.Groups[2].Value);
Debug.Log($"asset path: {assetPath}");
var asset = AssetDatabase.LoadAssetAtPath<GameObject>(assetPath);
if (asset)
{
AssetDatabase.TryGetGUIDAndLocalFileIdentifier(asset, out string _, out long localId);
line = line.Replace(match.Groups[1].Value, localId.ToString());
Debug.Log($"Output line: {line}");
}
}
outputStringStream.WriteLine(line);
}
inputStringStream.Close();
File.WriteAllText(contextAssetPath, outputStringStream.ToString());
AssetDatabase.Refresh();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment