Post-processing modifications to a prefab

2017-08-18T05:47:03+00:00 Aug 18, 2017|Nested Prefabs, Tips and Guides|

Sometimes it can be useful to have control over which properties are modified in a nested prefab. For example, if you require one property to always be unique for each prefab instance. You can add a Prefab Override to every single nested prefab in order to achieve this result, but if you already know that a property should be unique by default it will save a lot of time to ignore changes to this property automatically.

In order to ignore a property, we can create a new modification post-processor. The post-processor is called by the Nested Prefabs plugin after all modifications to a prefab have been found and before applying them to the nested prefabs in the project. The post-processor can be created by adding a custom attribute to a class:

Any class with this attribute will be called automatically when post-processing modifications. The class can have a few different methods to influence the modification of prefabs. The most useful one and the method we will use for this situation is:

The method takes a few parameters, the first prefab is the destination prefab that the modifications will be applied to. The modifications array contains all modifications that will be applied. source is the source prefab that was modified and applied. After modifying the modifications we have to return the modifications array. The modifications in the array that will be returned will be applied to the destination prefab.

With this information, we can edit the modifications made to a nested prefab. The goal is to remove modifications to properties that should be unique for every nested prefab. The first step is to get a collection of properties that should be ignored, separated by component. Here I have chosen to put them in a dictionary, with the component type as key and a string array with the properties as value.

Now that we have a collection of properties that should be ignored we can loop through all modifications to remove the properties that are in the collection. To easily filter the modifications we use the Enumerable.Where method from the LINQ library. When looping through the modifications it is important to skip all modifications with a type other than ModificationType.PropertyValueChanged. We only want to filter the modifications to the properties and not other modifications such as added children or components.

The final Modification Post-processor script looks like this, note that this is an editor script and should be placed inside an Editor folder in your project: