- Home /
How to programmatically change name of sub-assets
I am trying to change the name of the sub-sprites of a sprite sheet. I have searched and tried everything I can think of and cannot get it to work, which makes me think it can't be done at this point in time.
Let's say I have a sprite sheet that has already been split up into individual sprites inside of Unity.
I am attempting to change the sub-sprite names programmatically.
I tried using
AssetDatabase.RenameAsset (...)
on the sprite sheet asset, which only changes the sprite sheet name and not sub-sprites.
I then obtained a sub-sprite and attempted to change its name using the below code.
if (AssetDatabase.IsSubAsset (subSprite))
{
AssetDatabase.RenameAsset (AssetDatabase.GetAssetPath (subSprite), "newSprite" + i.ToString ());
}
However, this too only changes the sprite sheet name.
I'm not sure where else I can take this to achieve my desired outcome, apart from programmatically copying the original sprite sheet and using that to create a copy. But even then, I still am unable to alter the sub-sprite names.
I also tried changing subSprite.name, but this just changes the internal name and not the asset name.
Any ideas?
Anyone know of a solution? Apart from manually doing it...
Answer by Carl-Gran · Apr 13, 2016 at 11:47 AM
try:
AssetDatabase.ClearLabels(item);
item.name = newName;
AssetDatabase.SetLabels(item, new string[]{newName});
AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(item));
Where item is the object reference of your sub asset.
If anyone stumbles across this old thread, this solution is working in unity 2020-2021 as far as I know, a lot simpler than the previous solution if you're working with Scriptable Objects with a lot of sub assets.
Answer by ParkyRander · Aug 21, 2018 at 01:17 PM
string path = AssetDatabase.GetAssetPath(mainAsset);
UnityEngine.Object[] assets = AssetDatabase.LoadAllAssetsAtPath(path);
string prefix = string.Format("{0}_", mainAsset.name);
for(int i = 0; i < assets.Length; i++)
{
if (AssetDatabase.IsSubAsset(assets[i]))
{
if (assets[i].name.StartsWith(prefix) == false)
{
assets[i].name = prefix + assets[i].name;
EditorUtility.SetDirty(assets[i]);
}
}
}
EditorUtility.SetDirty(mainAsset);
AssetDatabase.ImportAsset(path);
This worked for me, so long as you have access to the mainAsset.