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.

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