Unity Tips 2

Thursday, June 18, 2015

OnValidate

You know when you make a component, then you add it to 35 prefabs, then you add another value to it and it needs to be initialized or something. That sucks eh? Well OnValidate gets called (only in the editor) every time you save or edit your component. What's cool is that if you edit your component (like when you change this function) all the prefabs get this called on them. So you can use it to validate and correct your prefabs.
void OnValidate() { myvalue = 5; if ( GetComponent() == null ) Debug.LogWarning( "MISSING COMPONENT!", gameObject ); ForceLabel( gameObject, "MyComponentLabel" ); ForceBundle( gameObject, "shared/entity.bundle" ); }
You might want to set up some nice little functions, so you can automatically tag prefabs containing a component.
internal static void ForceLabel( UnityEngine.Object obj, string label ) { if ( UnityEditor.PrefabUtility.GetPrefabType( obj ) != UnityEditor.PrefabType.Prefab ) return; var labels = UnityEditor.AssetDatabase.GetLabels( obj ); if ( !labels.Contains( label ) ) { var labelList = labels.ToList(); labelList.Add( label ); UnityEditor.AssetDatabase.SetLabels( obj, labelList.ToArray() ); UnityEditor.EditorUtility.SetDirty( obj ); UnityEngine.Debug.LogWarning( "Forcing Label On Object: " + label + " - " + obj ); } }
Or maybe force the asset into a specific bundle.
internal static void ForceBundle( UnityEngine.Object obj, string label ) { if ( UnityEditor.PrefabUtility.GetPrefabType( obj ) != UnityEditor.PrefabType.Prefab ) return; var path = UnityEditor.AssetDatabase.GetAssetPath( obj ); var importer = UnityEditor.AssetImporter.GetAtPath( path ); if ( importer && importer.assetBundleName != label ) { importer.assetBundleName = label; } }

Duplicate With References

I ran into a problem recently. I had all the info for a specific entity in a folder a Pumpkin. It had its entity prefab, which referenced some ScriptableObject properties, an icon and some other related prefabs. All in one folder. So then I wanted to make another version of this entity, some Corn. This was pretty much set up the same so all I had to do was copy the folder and edit the filenames. Then I realised that all the prefabs and stuff in the duplicated folder were still referencing the other files in the Pumpkin folder. Well that sucked. So I made this tool which duplicates a folder then goes through all the objects in the new folder, and if they point to anything in the old folder we change the reference to point to the file in our folder. Source code is here (right click folder, tools > duplicate with references)

FindAndReplace

So after I did that I had my Corn folder, but all the files inside were all named "pumpkin.icon.png". So I made FindAndReplace, which not only renames the files but also can replace text in any strings in the prefab's components and ScriptableObjects. Source code is here
Turn your phone to view blog list