Destructible Tool Asset
The objective for this project was to create a quick setup tool for assets that need to be shattered. The scope ended up expanding into also including a 'Destructible Manager', which handles pooling the spawned objects, as well as a bunch of parameters users can set for each destroyed object.
There are 3 components that need to be setup by this tool:
1) The undestroyed asset
2) A prefab of the destroyed asset
3) The destructible manager
1) The undestroyed asset
This is the original asset that will be in the scene. The only things that need to be added are a sphere collider and the 'destructible' script, which is filled by the destroyed prefab that will be created.
2) Prefab of the destroyed asset
In the prefab, all the pre-broken 'chunks' are children objects of the main parent. The only thing the user needs to do is add the 'Destructible Object Setup' script onto the parent, and hit 'Populate children components'. They may choose also to adjust the size of the spawned sphere colliders.
The script does the following:
-Adds a 'Destroyed Object' component to the same parent object
-on each child object, checks for a 'mesh renderer' component
-if a mesh renderer is found (meaning this object is a valid mesh), adds a sphere collider, destroyed chunk, and rigidbody component.
No further setup is required on this prefab, unless the user wants to modify the behavior of the spawned chunks by modifying some parameters on the 'Destroyed Object' component. (examples of variations below)
Below are some variations of the Destroyed Objects parameter. It's important to note that since this is using physics, the way the original object is hit will vary how the chunks scatter when destroyed. All the below gifs represent a bullet flying through the object in exactly the same way to illustrate the variation.
3) Destructible Manager
I felt it necessary to add a singleton manager, for a couple reasons. First, it allowed me to make a simple but effective pool system, and Second, I could have a single entity that can be interacted with when an object needs to be destroyed, instead of having similar code potentially scattered around different classes.
One other feature this allowed me to add is the ability to filter layers to check to see if a valid collision wants to destruct.
Below is the chunk of code in this manager that handles the pooling, and actually spawns the destroyed chunks. Pooling is useful, because it allows this class to reuse already spawned objects if possible, which can potentially save some overhead.