This commit is contained in:
2025-09-17 18:56:28 +08:00
commit 54c72710a5
5244 changed files with 5717609 additions and 0 deletions

View File

@@ -0,0 +1,17 @@
fileFormatVersion: 2
guid: b532092fde343e744b961afbbf8adeb7
labels:
- Destruction
- Destroy
- Physics
- DestroyIt
- Damage
- Fracturing
- Demolition
folderAsset: yes
timeCreated: 1427397479
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,51 @@
using System;
using UnityEngine;
using UnityEditor;
namespace DestroyIt
{
[InitializeOnLoad]
public class CreateLayers
{
private static readonly string[] layersToCreate = {"DestroyItDebris"}; // put your layers here (comma-separated)
private static SerializedObject tagManager;
static CreateLayers()
{
for (int i = 0; i < layersToCreate.Length; i++)
{
int layer = LayerMask.NameToLayer(layersToCreate[i]);
if (layer != -1) // Layer already exists, so exit.
return;
// Layer doesn't exist, so create it.
CreateLayer(layersToCreate[i]);
}
}
static void CreateLayer(string layerName)
{
if (tagManager == null)
tagManager = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/TagManager.asset")[0]);
if (tagManager == null)
{
Debug.Log("Could not load asset 'ProjectSettings/TagManager.asset'.");
return;
}
SerializedProperty layersProp = tagManager.FindProperty("layers");
for (int i = 8; i <= 31; i++)
{
SerializedProperty sp = layersProp.GetArrayElementAtIndex(i);
if (sp != null && String.IsNullOrEmpty(sp.stringValue))
{
sp.stringValue = layerName;
break;
}
}
tagManager.ApplyModifiedProperties();
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 3204e60668457ef4e881f03e5ee9334c
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,18 @@
{
"name": "Destroy.Editor",
"rootNamespace": "",
"references": [
"GUID:3a5d3214f3d7fb845bf8991981763e58"
],
"includePlatforms": [
"Editor"
],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 6c18a62bc019e3940ad04db036242301
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,762 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.SceneManagement;
// ReSharper disable SuggestVarOrType_BuiltInTypes
namespace DestroyIt
{
[CustomEditor(typeof(Destructible)), CanEditMultipleObjects]
public class DestructibleEditor : Editor
{
private GameObject previousDestroyedPrefab;
private SerializedProperty fallbackParticle;
private SerializedProperty fallbackParticleMatOption;
private SerializedProperty totalHitPoints;
private SerializedProperty currentHitPoints;
private SerializedProperty ignoreCollisionsUnder;
private SerializedProperty canBeDestroyed;
private SerializedProperty canBeRepaired;
private SerializedProperty isDebrisChipAway;
private SerializedProperty chipAwayDebrisMass;
private SerializedProperty chipAwayDebrisDrag;
private SerializedProperty chipAwayDebrisAngularDrag;
private SerializedProperty autoPoolDestroyedPrefab;
private SerializedProperty useFallbackParticle;
private SerializedProperty centerPointOverride;
private SerializedProperty fallbackParticleScale;
private SerializedProperty fallbackParticleParent;
private SerializedProperty sinkWhenDestroyed;
private SerializedProperty destroyedPrefabParent;
private SerializedProperty limitDamage;
private SerializedProperty maxDamage;
private SerializedProperty minDamage;
private SerializedProperty minDamageTime;
public void OnEnable()
{
fallbackParticle = serializedObject.FindProperty("fallbackParticle");
fallbackParticleMatOption = serializedObject.FindProperty("fallbackParticleMatOption");
totalHitPoints = serializedObject.FindProperty("_totalHitPoints");
currentHitPoints = serializedObject.FindProperty("_currentHitPoints");
ignoreCollisionsUnder = serializedObject.FindProperty("ignoreCollisionsUnder");
canBeDestroyed = serializedObject.FindProperty("canBeDestroyed");
canBeRepaired = serializedObject.FindProperty("canBeRepaired");
isDebrisChipAway = serializedObject.FindProperty("isDebrisChipAway");
chipAwayDebrisMass = serializedObject.FindProperty("chipAwayDebrisMass");
chipAwayDebrisDrag = serializedObject.FindProperty("chipAwayDebrisDrag");
chipAwayDebrisAngularDrag = serializedObject.FindProperty("chipAwayDebrisAngularDrag");
autoPoolDestroyedPrefab = serializedObject.FindProperty("autoPoolDestroyedPrefab");
useFallbackParticle = serializedObject.FindProperty("useFallbackParticle");
centerPointOverride = serializedObject.FindProperty("centerPointOverride");
fallbackParticleScale = serializedObject.FindProperty("fallbackParticleScale");
sinkWhenDestroyed = serializedObject.FindProperty("sinkWhenDestroyed");
destroyedPrefabParent = serializedObject.FindProperty("destroyedPrefabParent");
fallbackParticleParent = serializedObject.FindProperty("fallbackParticleParent");
limitDamage = serializedObject.FindProperty("limitDamage");
minDamage = serializedObject.FindProperty("minDamage");
maxDamage = serializedObject.FindProperty("maxDamage");
minDamageTime = serializedObject.FindProperty("minDamageTime");
}
public override void OnInspectorGUI()
{
serializedObject.Update();
Destructible destructible = target as Destructible;
bool hasRigidbody = destructible.GetComponent<Rigidbody>() != null;
List<string> materialOptions = new List<string>();
List<string> particleMatOptions = new List<string>();
List<string> debrisOptions = new List<string>();
List<string> destructibleChildrenOptions = new List<string>();
#region BASIC DESTRUCTIBLE ATTRIBUTES
EditorGUILayout.Separator();
EditorGUILayout.BeginVertical("Box");
EditorGUILayout.LabelField("Basic Attributes", EditorStyles.boldLabel);
// TOTAL HIT POINTS
EditorGUILayout.PropertyField(totalHitPoints, new GUIContent("Total Hit Points", "The maximum, or starting hit points, of the object."));
if (totalHitPoints.floatValue < 0)
totalHitPoints.floatValue = 0;
if (Math.Abs(totalHitPoints.floatValue - destructible.TotalHitPoints) > 0.01f) // value has changed, so change the current hit points to match.
currentHitPoints.floatValue = totalHitPoints.floatValue;
destructible.TotalHitPoints = totalHitPoints.floatValue;
// CURRENT HIT POINTS
EditorGUILayout.PropertyField(currentHitPoints, new GUIContent("Current Hit Points", "The current hit points of the object."));
if (currentHitPoints.floatValue > destructible.TotalHitPoints)
currentHitPoints.floatValue = destructible.TotalHitPoints;
if (currentHitPoints.floatValue < 0)
currentHitPoints.floatValue = 0;
destructible.CurrentHitPoints = currentHitPoints.floatValue;
// CAN BE DESTROYED
canBeDestroyed.boolValue = EditorGUILayout.Toggle(new GUIContent("Can Be Destroyed", "If checked, the object can be damaged until it is destroyed. If unchecked, the object can still be damaged and will display any progressive damage and damage effects, but cannot be destroyed."), canBeDestroyed.boolValue);
destructible.canBeDestroyed = canBeDestroyed.boolValue;
// CAN BE REPAIRED
canBeRepaired.boolValue = EditorGUILayout.Toggle(new GUIContent("Can Be Repaired", "If checked, this object is capable of being repaired. If unchecked, this object will ignore any attempt to repair it."), canBeRepaired.boolValue);
destructible.canBeRepaired = canBeRepaired.boolValue;
// SINK INTO GROUND INSTEAD OF DESTROYING INTO DEBRIS
if (hasRigidbody && destructible.canBeDestroyed)
{
GUILayout.BeginHorizontal();
sinkWhenDestroyed.boolValue = EditorGUILayout.Toggle(new GUIContent("Sink on Destroy", "If checked, this object will sink into the ground when destroyed, instead of emitting a particle effect or swapping to a destroyed prefab. Requires a rigidbody on the object."), sinkWhenDestroyed.boolValue);
GUILayout.EndHorizontal();
destructible.sinkWhenDestroyed = sinkWhenDestroyed.boolValue;
}
else
destructible.sinkWhenDestroyed = false;
// VELOCITY REDUCTION
destructible.velocityReduction = EditorGUILayout.Slider(new GUIContent("Velocity Reduction", "How much this object reduces the velocity of fast-moving objects that impact and destroy it."), destructible.velocityReduction, 0f, 1f);
// IGNORE COLLISIONS UNDER
GUILayout.BeginHorizontal();
GUILayout.Label(new GUIContent("Ignore Collisions Under", "Collisions with this object will be ignored if they are under this magnitude. Useful for things like tires, which constantly have small-to-medium collisions with the terrain."), GUILayout.Width(140));
GUILayout.FlexibleSpace();
EditorGUILayout.PropertyField(ignoreCollisionsUnder, GUIContent.none, true, GUILayout.MinWidth(10));
GUILayout.FlexibleSpace();
GUILayout.Label("Magnitude", GUILayout.Width(65));
GUILayout.EndHorizontal();
destructible.ignoreCollisionsUnder = ignoreCollisionsUnder.floatValue;
// MIN AND MAX DAMAGE
limitDamage.boolValue = EditorGUILayout.Toggle(new GUIContent("Limit Damage", "Provides options for the minimum and maximum damage the object will take per hit, as well as the amount of time that must pass before taking more damage."), limitDamage.boolValue);
destructible.limitDamage = limitDamage.boolValue;
if (destructible.limitDamage)
{
EditorGUILayout.BeginHorizontal();
if (destructible.maxDamage < 0f)
GUI.color = Color.red;
EditorGUILayout.LabelField("", GUILayout.Width(15));
destructible.maxDamage = EditorGUILayout.FloatField(new GUIContent("Max Damage", "The maximum amount of damage the object can receive per hit. Must be greater than or equal to zero. If zero, the object will not take any damage."), maxDamage.floatValue);
GUI.color = Color.white;
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
if (destructible.minDamage < 0f || destructible.minDamage > destructible.maxDamage)
GUI.color = Color.red;
EditorGUILayout.LabelField("", GUILayout.Width(15));
destructible.minDamage = EditorGUILayout.FloatField(new GUIContent("Min Damage", "The minimum amount of damage the object will receive per hit. Must be greater than or equal to zero. Must be less than or equal to the Max Damage limit."), minDamage.floatValue);
GUI.color = Color.white;
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
if (destructible.minDamageTime < 0f)
GUI.color = Color.red;
EditorGUILayout.LabelField("", GUILayout.Width(15));
destructible.minDamageTime = EditorGUILayout.FloatField(new GUIContent("Min Time Between", "After being damaged, the minimum amount of time (in seconds) that must pass before the object can be damaged again. Must be greater than or equal to zero."), minDamageTime.floatValue);
GUI.color = Color.white;
EditorGUILayout.EndHorizontal();
}
EditorGUILayout.Separator();
EditorGUILayout.EndVertical();
EditorGUILayout.Separator();
#endregion
#region AUDIO
EditorGUILayout.Separator();
EditorGUILayout.BeginVertical("Box");
EditorGUILayout.LabelField("Audio", EditorStyles.boldLabel);
destructible.destroyedSound = (AudioClip)EditorGUILayout.ObjectField(new GUIContent("Destroyed Sound", "The audio clip that will play when this destructible object is destroyed."), destructible.destroyedSound, typeof(AudioClip), false);
destructible.damagedSound = (AudioClip)EditorGUILayout.ObjectField(new GUIContent("Damaged Sound", "The audio clip that will play with this destructible object is damaged."), destructible.damagedSound, typeof(AudioClip), false);
destructible.repairedSound = (AudioClip)EditorGUILayout.ObjectField(new GUIContent("Repaired Sound", "The audio clip that will play when this destructible object is repaired."), destructible.repairedSound, typeof(AudioClip), false);
EditorGUILayout.Separator();
EditorGUILayout.EndVertical();
EditorGUILayout.Separator();
#endregion
#region DAMAGE LEVELS
// Initialize and default the damage levels if needed.
if (destructible.damageLevels == null || destructible.damageLevels.Count == 0)
destructible.damageLevels = DestructibleHelper.DefaultDamageLevels();
EditorGUILayout.BeginVertical("Box");
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Damage Levels", EditorStyles.boldLabel);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("HP %", GUILayout.Width(40));
EditorGUILayout.LabelField("HP Range", GUILayout.Width(66));
// Find out if there are any materials on the destructible object that are capable of showing visual damage levels.
Renderer[] renderers = destructible.GetComponentsInChildren<Renderer>();
destructible.UseProgressiveDamage = false;
foreach (Renderer rend in renderers)
{
foreach (Material mat in rend.sharedMaterials)
{
if (!mat.IsProgressiveDamageCapable()) continue;
destructible.UseProgressiveDamage = true;
break;
}
}
GUIContent visibleDamageContent = new GUIContent("Visible Damage", "Visible Damage Levels require using the Standard shader for your materials. You also need to use the Detail Mask to control visibility, and both Secondary Maps to add damage.");
EditorGUILayout.LabelField( visibleDamageContent, GUILayout.Width(100));
EditorGUILayout.EndHorizontal();
int[] popupValues = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
string[] popupDisplay = {"0 Undamaged","1 Light","2 Light","3 Light","4 Medium","5 Medium","6 Medium","7 Heavy","8 Heavy","9 Heavy"};
int lowestHealthPercent = 100;
for (int i=0; i<destructible.damageLevels.Count; i++)
{
EditorGUILayout.BeginHorizontal();
if (i > 0)
{
if (destructible.damageLevels[i].hasError)
GUI.color = Color.red;
destructible.damageLevels[i].healthPercent = EditorGUILayout.IntField(destructible.damageLevels[i].healthPercent, GUILayout.Width(40));
GUI.color = Color.white;
}
else
{
EditorGUI.BeginDisabledGroup(true);
destructible.damageLevels[i].healthPercent = 100;
EditorGUILayout.IntField(destructible.damageLevels[i].healthPercent, GUILayout.Width(40));
EditorGUI.EndDisabledGroup();
}
EditorGUILayout.LabelField(destructible.damageLevels[i].maxHitPoints + "-" + destructible.damageLevels[i].minHitPoints, GUILayout.Width(66));
if (!destructible.UseProgressiveDamage)
GUI.enabled = false;
destructible.damageLevels[i].visibleDamageLevel = EditorGUILayout.IntPopup(destructible.damageLevels[i].visibleDamageLevel, popupDisplay, popupValues);
GUI.enabled = true;
EditorGUILayout.EndHorizontal();
lowestHealthPercent = destructible.damageLevels[i].healthPercent;
}
// Add/Remove buttons
EditorGUILayout.Space();
bool showAddDamageLevel = destructible.damageLevels.Count <= 10;
bool showRemoveDamageLevel = destructible.damageLevels.Count > 1;
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("", GUILayout.Width(15));
if (showAddDamageLevel && GUILayout.Button("+", EditorStyles.toolbarButton, GUILayout.Width(30)))
destructible.damageLevels.Add(new DamageLevel {healthPercent = Mathf.RoundToInt(lowestHealthPercent/2f)});
if (showRemoveDamageLevel && GUILayout.Button("-", EditorStyles.toolbarButton, GUILayout.Width(30)))
destructible.damageLevels.RemoveAt(destructible.damageLevels.Count - 1);
GUILayout.FlexibleSpace();
if (GUILayout.Button("Reset", EditorStyles.toolbarButton, GUILayout.Width(50)))
destructible.damageLevels = DestructibleHelper.DefaultDamageLevels();
EditorGUILayout.LabelField("", GUILayout.Width(15));
EditorGUILayout.EndHorizontal();
EditorGUILayout.Separator();
// DAMAGE EFFECTS
if (destructible.damageEffects == null)
destructible.damageEffects = new List<DamageEffect>();
string[] dropDownValues = new string[destructible.damageLevels.Count+1];
for (int i=0; i<destructible.damageLevels.Count; i++)
dropDownValues[i] = destructible.damageLevels[i].healthPercent + "%";
dropDownValues[destructible.damageLevels.Count] = "Destroyed";
EditorGUILayout.LabelField("Damage Effects", EditorStyles.boldLabel);
foreach (DamageEffect damageParticle in destructible.damageEffects)
{
EditorGUILayout.BeginVertical("Box");
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField(new GUIContent("Effect", "The effect that will play at the specified damage level."), GUILayout.Width(60));
damageParticle.Prefab = EditorGUILayout.ObjectField(damageParticle.Prefab, typeof(GameObject), false) as GameObject;
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField(new GUIContent("Play at HP %", "When the destructible object is damaged to this point, this effect will play."), GUILayout.Width(100));
// Get the selected index of the dropdown, or default to the first one.
if (damageParticle.TriggeredAt < 0 || damageParticle.TriggeredAt > destructible.damageLevels.Count)
damageParticle.TriggeredAt = destructible.damageLevels.Count;
damageParticle.TriggeredAt = EditorGUILayout.Popup(damageParticle.TriggeredAt, dropDownValues);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField(new GUIContent("Offset", "Here you can specify how much to move the damage effect in relation to the destructible object, so it plays in the right spot."), GUILayout.Width(40));
damageParticle.Offset = EditorGUILayout.Vector3Field("", damageParticle.Offset, GUILayout.Width(142), GUILayout.Height(18));
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField(new GUIContent("Rotate", "Here you can rotate the damage effect independent from the destructible object, so it plays facing the right direction."), GUILayout.Width(40));
damageParticle.Rotation = EditorGUILayout.Vector3Field("", damageParticle.Rotation, GUILayout.Width(142), GUILayout.Height(18));
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField(new GUIContent("Scale", "Here you can override the scale of the damage effect independent from the destructible object, so it plays at the right size."), GUILayout.Width(40));
damageParticle.Scale = EditorGUILayout.Vector3Field("", damageParticle.Scale, GUILayout.Width(142), GUILayout.Height(18));
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
damageParticle.HasTagDependency = EditorGUILayout.Toggle(damageParticle.HasTagDependency, GUILayout.Width(15));
EditorGUILayout.LabelField(new GUIContent("Only If Tagged", "If checked, this effect will only play if the destructible object has the specified Tag."), GUILayout.Width(95));
damageParticle.TagDependency = (Tag)EditorGUILayout.EnumPopup(damageParticle.TagDependency);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
damageParticle.UnparentOnDestroy = EditorGUILayout.Toggle(damageParticle.UnparentOnDestroy, GUILayout.Width(15));
EditorGUILayout.LabelField(new GUIContent("Unparent when destroyed", "If checked, effect will be unparented when the object is destroyed. If unchecked, effect will be destroyed immediately with the object, which will stop any emissions abruptly."), GUILayout.Width(180));
EditorGUILayout.EndHorizontal();
if (damageParticle.UnparentOnDestroy)
{
EditorGUILayout.BeginHorizontal();
damageParticle.StopEmittingOnDestroy = EditorGUILayout.Toggle(damageParticle.StopEmittingOnDestroy, GUILayout.Width(15));
EditorGUILayout.LabelField(new GUIContent("Stop emitting when destroyed", "If checked, effect will stop emitting particles and be disabled when object is destroyed, allowing particles to disperse over time."), GUILayout.Width(180));
EditorGUILayout.EndHorizontal();
}
EditorGUILayout.Space();
EditorGUILayout.EndVertical();
}
// Add/Remove buttons
EditorGUILayout.Space();
bool showRemoveEffectButton = destructible.damageEffects.Count > 0;
CreateButtons(destructible.damageEffects, true, showRemoveEffectButton);
EditorGUILayout.Separator();
EditorGUILayout.EndVertical();
EditorGUILayout.Separator();
#endregion
#region DESTROYED PREFAB
// DESTROYED PREFAB
EditorGUILayout.BeginVertical("Box");
EditorGUILayout.LabelField("Destroyed Prefab", EditorStyles.boldLabel);
destructible.destroyedPrefab = EditorGUILayout.ObjectField(destructible.destroyedPrefab, typeof(GameObject), false) as GameObject;
if (previousDestroyedPrefab == null)
previousDestroyedPrefab = destructible.destroyedPrefab;
if (destructible.destroyedPrefab != null)
{
#region REPLACE MATERIALS ON DESTROYED PREFAB
// REPLACE MATERIALS ON DESTROYED PREFAB
//Get string array of material names on destroyed prefab
List<Renderer> destroyedMeshes = destructible.destroyedPrefab.GetComponentsInChildren<Renderer>(true).ToList();
destroyedMeshes.RemoveAll(x => x.GetType() != typeof(MeshRenderer) && x.GetType() != typeof(SkinnedMeshRenderer));
List<Material> destroyedMaterials = new List<Material>();
foreach (Renderer mesh in destroyedMeshes)
{
foreach (Material mat in mesh.sharedMaterials)
{
if (mat != null && !destroyedMaterials.Contains(mat))
{
destroyedMaterials.Add(mat);
materialOptions.Add(mat.name);
}
}
}
// Initialize replaceMaterials if null
if (destructible.replaceMaterials == null)
destructible.replaceMaterials = new List<MaterialMapping>();
// Clean up replaceMaterials
if (destructible.replaceMaterials.Count > 0)
destructible.replaceMaterials.RemoveAll(x => x.SourceMaterial != null && !materialOptions.Contains(x.SourceMaterial.name));
EditorGUILayout.Separator();
EditorGUILayout.LabelField("Material Replacement", EditorStyles.boldLabel);
if (destroyedMaterials.Count > 0)
{
destroyedMaterials = destroyedMaterials.OrderBy(x => x.name).ToList();
materialOptions.Sort();
foreach (MaterialMapping mapping in destructible.replaceMaterials)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("", GUILayout.Width(15));
EditorGUILayout.LabelField("Replace", GUILayout.Width(50));
int selectedMaterialIndex = mapping.SourceMaterial == null ? 0 : destroyedMaterials.IndexOf(mapping.SourceMaterial);
selectedMaterialIndex = EditorGUILayout.Popup(selectedMaterialIndex, materialOptions.ToArray());
if (selectedMaterialIndex >= 0 && selectedMaterialIndex < materialOptions.Count)
{
string materialName = materialOptions[selectedMaterialIndex];
mapping.SourceMaterial = destroyedMaterials.First(x => x.name == materialName);
}
else
mapping.SourceMaterial = null;
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("", GUILayout.Width(15));
EditorGUILayout.LabelField("With", GUILayout.Width(50));
mapping.ReplacementMaterial = EditorGUILayout.ObjectField(mapping.ReplacementMaterial, typeof(Material), false) as Material;
EditorGUILayout.EndHorizontal();
}
// Add/Remove buttons
bool showAddButton = destructible.replaceMaterials.Count < materialOptions.Count;
bool showRemoveButton = destructible.replaceMaterials.Count > 0;
CreateButtons(destructible.replaceMaterials, showAddButton, showRemoveButton);
}
else
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("", GUILayout.Width(15));
EditorGUILayout.LabelField("No materials found on prefab!", GUILayout.Width(200), GUILayout.Height(16));
EditorGUILayout.EndHorizontal();
}
EditorGUILayout.Separator();
#endregion
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(destroyedPrefabParent, new GUIContent("Assigned Parent:", "When destroyed, the destroyed prefab will spawn in as a child of this game object. If blank, the destroyed prefab will have no parent."));
destructible.destroyedPrefabParent = destroyedPrefabParent.objectReferenceValue as GameObject;
EditorGUILayout.EndHorizontal();
#region DEBRIS TO RE-PARENT
// DEBRIS TO RE-ATTACH TO PARENT
List<Transform> debrisObjects = destructible.destroyedPrefab.GetComponentsInChildrenOnly<Transform>(true);
if (debrisObjects.Count > 0)
{
EditorGUILayout.LabelField(new GUIContent("Debris to Re-Parent:", "Here you can assign debris pieces that will be re-parented to this game object's parent when destroyed. For example, if a character has a sword that gets destroyed, you might want to re-parent the broken handle back to the character's hand bone."));
debrisOptions.Add("ALL DEBRIS");
foreach (Transform trans in debrisObjects)
debrisOptions.Add(trans.name);
debrisOptions = debrisOptions.Distinct().ToList();
// Initialize DebrisToReparentByName
if (destructible.debrisToReParentByName == null)
destructible.debrisToReParentByName = new List<string>();
if (destructible.debrisToReParentByName.Count > 0)
{
debrisOptions.Sort();
for (int i = 0; i < destructible.debrisToReParentByName.Count; i++)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("", GUILayout.Width(15));
EditorGUILayout.LabelField("Name", GUILayout.Width(50));
int currentSelectedIndex = debrisOptions.FindIndex(m => m == destructible.debrisToReParentByName[i]);
int selectedDebrisIndex = EditorGUILayout.Popup(currentSelectedIndex, debrisOptions.ToArray());
if (selectedDebrisIndex >= 0 && selectedDebrisIndex < debrisOptions.Count)
destructible.debrisToReParentByName[i] = debrisOptions[selectedDebrisIndex];
else
destructible.debrisToReParentByName[i] = debrisOptions[0];
EditorGUILayout.EndHorizontal();
}
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("", GUILayout.Width(15));
destructible.debrisToReParentIsKinematic = EditorGUILayout.Toggle(new GUIContent("Make Kinematic", "When FALSE, debris pieces that are reparented under this game object's parent will be affected by gravity/forces once the object is destroyed. Set to TRUE for things like a sword handle reparented to a rigged hand bone."), destructible.debrisToReParentIsKinematic);
EditorGUILayout.EndHorizontal();
}
// Add/Remove buttons
bool showReparentAddButton = destructible.debrisToReParentByName.Count < debrisOptions.Count;
bool showReparentRemoveButton = destructible.debrisToReParentByName.Count > 0;
CreateButtons(destructible.debrisToReParentByName, showReparentAddButton, showReparentRemoveButton);
}
#endregion
#region RE-PARENT CHILDREN TO DESTROYED PREFAB
//RE-PARENT CHILDREN TO DESTROYED PREFAB
List<Transform> destructibleChildren = destructible.gameObject.GetComponentsInChildrenOnly<Transform>(true);
if (destructibleChildren.Count > 0)
{
EditorGUILayout.LabelField(new GUIContent("Re-Parent to Destroyed Prefab:", "These child objects will be re-parented under the destroyed prefab at the same location. For example, consider a wooden door that has a small window in it. When destroyed, the door breaks into a few large pieces. The window could be destroyed separately, but if it is not, we want the window to be re-parented to the broken door."));
foreach (Transform trans in destructibleChildren)
destructibleChildrenOptions.Add(trans.name);
destructibleChildrenOptions = destructibleChildrenOptions.Distinct().ToList();
// Initialize ChildrenToReparentByName
if (destructible.childrenToReParentByName == null)
destructible.childrenToReParentByName = new List<string>();
if (destructible.childrenToReParentByName.Count > 0)
{
destructibleChildrenOptions.Sort();
for (int i = 0; i < destructible.childrenToReParentByName.Count; i++)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("", GUILayout.Width(15));
EditorGUILayout.LabelField("Name", GUILayout.Width(50));
int currentSelectedIndex = destructibleChildrenOptions.FindIndex(m => m == destructible.childrenToReParentByName[i]);
int selectedChildIndex = EditorGUILayout.Popup(currentSelectedIndex, destructibleChildrenOptions.ToArray());
if (selectedChildIndex >= 0 && selectedChildIndex < destructibleChildrenOptions.Count)
destructible.childrenToReParentByName[i] = destructibleChildrenOptions[selectedChildIndex];
else
destructible.childrenToReParentByName[i] = destructibleChildrenOptions[0];
EditorGUILayout.EndHorizontal();
}
}
// Add/Remove buttons
bool showChildReparentAddButton = destructible.childrenToReParentByName.Count < destructibleChildrenOptions.Count;
bool showChildReparentRemoveButton = destructible.childrenToReParentByName.Count > 0;
CreateButtons(destructible.childrenToReParentByName, showChildReparentAddButton, showChildReparentRemoveButton);
}
#endregion
#region CHIP-AWAY DEBRIS
//CHIP-AWAY DEBRIS
isDebrisChipAway.boolValue = EditorGUILayout.Toggle("Chip-Away Debris", isDebrisChipAway.boolValue);
destructible.isDebrisChipAway = isDebrisChipAway.boolValue;
if (destructible.isDebrisChipAway)
{
// CHIP-AWAY DEBRIS MASS
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("", GUILayout.Width(15));
chipAwayDebrisMass.floatValue = EditorGUILayout.FloatField("Debris Mass", chipAwayDebrisMass.floatValue);
destructible.chipAwayDebrisMass = chipAwayDebrisMass.floatValue;
EditorGUILayout.EndHorizontal();
// CHIP-AWAY DEBRIS DRAG
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("", GUILayout.Width(15));
chipAwayDebrisDrag.floatValue = EditorGUILayout.FloatField("Debris Drag", chipAwayDebrisDrag.floatValue);
destructible.chipAwayDebrisDrag = chipAwayDebrisDrag.floatValue;
EditorGUILayout.EndHorizontal();
// CHIP-AWAY DEBRIS ANGULARDRAG
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("", GUILayout.Width(15));
chipAwayDebrisAngularDrag.floatValue = EditorGUILayout.FloatField("Debris Angular Drag", chipAwayDebrisAngularDrag.floatValue);
destructible.chipAwayDebrisAngularDrag = chipAwayDebrisAngularDrag.floatValue;
EditorGUILayout.EndHorizontal();
}
#endregion
// AUTO-POOL DESTROYED PREFAB
autoPoolDestroyedPrefab.boolValue = EditorGUILayout.Toggle(new GUIContent("Auto Pool", "If checked, the destroyed prefab for this object will be added to the object pool automatically for you at runtime."), autoPoolDestroyedPrefab.boolValue);
destructible.autoPoolDestroyedPrefab = autoPoolDestroyedPrefab.boolValue;
previousDestroyedPrefab = destructible.destroyedPrefab;
}
EditorGUILayout.Separator();
EditorGUILayout.EndVertical();
EditorGUILayout.Separator();
#endregion
// MISCELLANEOUS
EditorGUILayout.BeginVertical("Box");
#region PARTICLES
EditorGUILayout.LabelField("Miscellaneous", EditorStyles.boldLabel);
// FALLBACK PARTICLE
EditorGUILayout.BeginHorizontal();
useFallbackParticle.boolValue = EditorGUILayout.Toggle("", useFallbackParticle.boolValue, GUILayout.Width(15));
GUIContent fallbackParticleContent = new GUIContent("Use Fallback Particle", "The particle effect used when this object is: (1) destroyed when there is no destroyed prefab assigned or (2) destroyed when a destroyed prefab is assigned but the DestructionManager's destroyed prefab limit has been reached. If unchecked, the object will disappear when destroyed. If checked but unassigned, the default particle effect will be used.");
EditorGUILayout.LabelField(fallbackParticleContent);
destructible.useFallbackParticle = useFallbackParticle.boolValue;
EditorGUILayout.EndHorizontal();
if (destructible.useFallbackParticle)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("", GUILayout.Width(15));
EditorGUILayout.PropertyField(fallbackParticle, new GUIContent(""));
destructible.fallbackParticle = fallbackParticle.objectReferenceValue as ParticleSystem;
if (destructible.fallbackParticle == null)
destructible.fallbackParticle = Resources.Load<ParticleSystem>("Default_Particles/DefaultLargeParticle");
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("", GUILayout.Width(15));
GUIContent fallbackParticleMatOptionGuiContent = new GUIContent("Replace Materials With:", "Allows you to override mesh renderer materials on the fallback particle effect.\n\nDestroyed Object - Mesh materials on the fallback particle will be replaced with the 0-index material from the destructible object.\n\nDon't Replace - Mesh materials will not be modified on the fallback particle.\n\nCustom - Specify each mesh material that will be replaced on the fallback particle, and by which alternative material.");
EditorGUILayout.LabelField(fallbackParticleMatOptionGuiContent);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
int[] popupParticleMatOptionValues = {0, 1, 2};
string[] popupParticleMatOptionDisplay = {"Destroyed Object", "Don't Replace", "Custom"};
EditorGUILayout.LabelField("", GUILayout.Width(15));
destructible.fallbackParticleMatOption = EditorGUILayout.IntPopup(fallbackParticleMatOption.intValue, popupParticleMatOptionDisplay, popupParticleMatOptionValues, GUILayout.Width(200));
EditorGUILayout.EndHorizontal();
// FALLBACK PARTICLE MATERIAL REPLACEMENT OPTIONS
if (destructible.fallbackParticleMatOption == 2)
{
List<ParticleSystemRenderer> psrs = destructible.fallbackParticle.GetComponentsInChildren<ParticleSystemRenderer>(true).ToList();
List<Material> particleMaterials = new List<Material>();
foreach (ParticleSystemRenderer psr in psrs)
{
if (psr.renderMode != ParticleSystemRenderMode.Mesh) continue;
foreach (Material mat in psr.sharedMaterials)
{
if (mat != null && !particleMaterials.Contains(mat))
{
particleMaterials.Add(mat);
particleMatOptions.Add(mat.name);
}
}
}
// Initialize replaceMaterials if null
if (destructible.replaceParticleMats == null)
destructible.replaceParticleMats = new List<MaterialMapping>();
// Clean up replaceMaterials
if (destructible.replaceParticleMats.Count > 0)
destructible.replaceParticleMats.RemoveAll(x => x.SourceMaterial != null && !particleMatOptions.Contains(x.SourceMaterial.name));
EditorGUILayout.Separator();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("", GUILayout.Width(15));
EditorGUILayout.LabelField("Material Replacement", EditorStyles.boldLabel);
EditorGUILayout.EndHorizontal();
if (particleMaterials.Count > 0)
{
particleMaterials = particleMaterials.OrderBy(x => x.name).ToList();
particleMatOptions.Sort();
foreach (MaterialMapping mapping in destructible.replaceParticleMats)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("", GUILayout.Width(15));
EditorGUILayout.LabelField("Replace", GUILayout.Width(50));
int selectedMaterialIndex = mapping.SourceMaterial == null ? 0 : particleMaterials.IndexOf(mapping.SourceMaterial);
selectedMaterialIndex = EditorGUILayout.Popup(selectedMaterialIndex, particleMatOptions.ToArray());
if (selectedMaterialIndex >= 0 && selectedMaterialIndex < particleMatOptions.Count)
{
string materialName = particleMatOptions[selectedMaterialIndex];
mapping.SourceMaterial = particleMaterials.First(x => x.name == materialName);
}
else
mapping.SourceMaterial = null;
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("", GUILayout.Width(15));
EditorGUILayout.LabelField("With", GUILayout.Width(50));
mapping.ReplacementMaterial = EditorGUILayout.ObjectField(mapping.ReplacementMaterial, typeof(Material), false) as Material;
EditorGUILayout.EndHorizontal();
}
// Add/Remove buttons
bool showAddButton = destructible.replaceParticleMats.Count < particleMatOptions.Count;
bool showRemoveButton = destructible.replaceParticleMats.Count > 0;
CreateButtons(destructible.replaceParticleMats, showAddButton, showRemoveButton);
}
else
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("", GUILayout.Width(15));
EditorGUILayout.LabelField("No materials found on particle!", GUILayout.Width(200), GUILayout.Height(16));
EditorGUILayout.EndHorizontal();
}
EditorGUILayout.Separator();
}
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("", GUILayout.Width(15));
destructible.centerPointOverride = EditorGUILayout.Vector3Field(new GUIContent("Position Override", "Here you can override the position the particle effect will spawn. This is particularly useful for Static objects, since DestroyIt uses the transform's position as the particle spawn point, which may not always be the center of the mesh."), centerPointOverride.vector3Value);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("", GUILayout.Width(15));
destructible.fallbackParticleScale = EditorGUILayout.Vector3Field(new GUIContent("Scale Override", "Here you can override the scale of the particle effect when it spawns."), fallbackParticleScale.vector3Value);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("", GUILayout.Width(15));
EditorGUILayout.PropertyField(fallbackParticleParent, new GUIContent("Parent Under", "Here you can specify a transform to parent the fallback particle effect under when it spawns.\n\nThis is helpful, for instance, if your destructible object is on a moving platform and you want the particle effect to move with the platform.\n\nNote that changing the parent transform will not change where the particle effect will spawn - it will still spawn at the destroyed object's position."));
destructible.fallbackParticleParent = fallbackParticleParent.objectReferenceValue as Transform;
EditorGUILayout.EndHorizontal();
}
EditorGUILayout.Separator();
#endregion
#region UNPARENT ON DESTROY
// UNPARENT ON DESTROY
List<Transform> children = destructible.gameObject.GetComponentsInChildrenOnly<Transform>();
List<string> childrenOptions = children.Select(x => $"{x.name} [{x.GetInstanceID()}]").ToList();
childrenOptions.Insert(0, "--Select--");
if (children.Count > 0)
{
bool rigidbodyFound = false;
EditorGUILayout.Separator();
EditorGUILayout.LabelField(new GUIContent("Un-Parent Children When Destroyed:", "These child objects will be un-parented from the destructible object when it is destroyed."));
List<GameObject> tempList = new List<GameObject>();
if (destructible.unparentOnDestroy == null)
destructible.unparentOnDestroy = new List<GameObject>();
foreach (GameObject go in destructible.unparentOnDestroy)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("", GUILayout.Width(15));
EditorGUILayout.LabelField("Child", GUILayout.Width(50));
int selectedchildIndex = go == null ? 0 : children.IndexOf(go.transform) + 1;
selectedchildIndex = EditorGUILayout.Popup(selectedchildIndex, childrenOptions.ToArray());
GameObject selectedChild = null;
if (selectedchildIndex > 0 && selectedchildIndex < childrenOptions.Count)
{
string childName = childrenOptions[selectedchildIndex];
const string pattern = @"\[-*[0-9]+\]";
string match = Regex.Match(childName, pattern).Value;
int instanceId = Convert.ToInt32(match.Trim('[', ']'));
selectedChild = children.First(x => x.GetInstanceID() == instanceId).gameObject;
Rigidbody rb = selectedChild.GetComponent<Rigidbody>();
if (rb != null) rigidbodyFound = true;
}
EditorGUILayout.EndHorizontal();
tempList.Add(selectedChild);
}
if (rigidbodyFound)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("", GUILayout.Width(15));
destructible.disableKinematicOnUparentedChildren = EditorGUILayout.Toggle(new GUIContent("Turn off Kinematic", "When TRUE, kinematic rigidbodies on unparented children will be affected by gravity/forces once the object is destroyed."), destructible.disableKinematicOnUparentedChildren);
EditorGUILayout.EndHorizontal();
}
else
destructible.disableKinematicOnUparentedChildren = true; // default to TRUE when future children are added to unparent.
destructible.unparentOnDestroy = tempList;
// Add/Remove buttons
bool showAddButton = destructible.unparentOnDestroy.Count < children.Count;
bool showRemoveButton = destructible.unparentOnDestroy.Count > 0;
CreateButtons(destructible.unparentOnDestroy, showAddButton, showRemoveButton);
EditorGUILayout.Separator();
}
#endregion
EditorGUILayout.EndVertical();
EditorGUILayout.Separator();
if (GUI.changed && !Application.isPlaying)
{
EditorUtility.SetDirty(destructible);
EditorSceneManager.MarkSceneDirty(SceneManager.GetActiveScene());
}
serializedObject.ApplyModifiedProperties();
}
private void CreateButtons<T>(List<T> itemList, bool showAddButton, bool showRemoveButton)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("", GUILayout.Width(15));
if (showAddButton && GUILayout.Button("+", EditorStyles.toolbarButton, GUILayout.Width(30)))
itemList.Add(default);
if (showRemoveButton && GUILayout.Button("-", EditorStyles.toolbarButton, GUILayout.Width(30)))
itemList.RemoveAt(itemList.Count - 1);
EditorGUILayout.EndHorizontal();
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: d43695d595a398a4885848fd6c558454
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,78 @@
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace DestroyIt
{
[CustomEditor(typeof(DestructionManager))]
public class DestructionManagerEditor : Editor
{
public override void OnInspectorGUI()
{
DestructionManager destManager = target as DestructionManager;
EditorGUILayout.Separator();
EditorGUILayout.BeginVertical("Box");
EditorGUILayout.Separator();
EditorGUILayout.LabelField(new GUIContent("Auto-Deactivate", "Provides options to gain better performance by deactivating Destructible scripts when they are far away from the player."), EditorStyles.boldLabel);
GUILayout.BeginHorizontal();
destManager.autoDeactivateDestructibles = EditorGUILayout.Toggle(destManager.autoDeactivateDestructibles, GUILayout.Width(20));
EditorGUILayout.LabelField(new GUIContent("Destructible Objects", "If true, Destructible scripts will be deactivated on start, and will re-activate any time they are inside a trigger collider with the ActivateDestructibles script on it."));
GUILayout.EndHorizontal();
if (destManager.autoDeactivateDestructibles)
{
GUILayout.Label(new GUIContent("NOTE: You'll need to put a trigger collider with ActivateDestructibles script to re-activate Destructibles within range. See the ActivateDestructiblesArea prefab for an example."), EditorStyles.helpBox);
}
GUILayout.BeginHorizontal();
destManager.autoDeactivateDestructibleTerrainObjects = EditorGUILayout.Toggle(destManager.autoDeactivateDestructibleTerrainObjects, GUILayout.Width(20));
EditorGUILayout.LabelField(new GUIContent("Destructible Terrain Objects", "If true, Destructible terrain object scripts will be deactivated on start, and will activate any time they are inside a trigger collider with the ActivateDestructibles script on it."));
GUILayout.EndHorizontal();
if (destManager.autoDeactivateDestructibleTerrainObjects)
{
GUILayout.BeginHorizontal();
EditorGUILayout.LabelField("", GUILayout.Width(15));
destManager.destructibleTreesStayDeactivated = EditorGUILayout.Toggle(destManager.destructibleTreesStayDeactivated, GUILayout.Width(20));
EditorGUILayout.LabelField(new GUIContent("Don't Reactivate Terrain Objects", "If true, Destructible terrain object scripts will not be re-activated by ActivateDestructibles scripts. Recommended to leave this true for performance, unless you need to move terrain objects during the game or use progressive damage textures on them."));
GUILayout.EndHorizontal();
}
if (destManager.autoDeactivateDestructibles || destManager.autoDeactivateDestructibleTerrainObjects)
{
GUILayout.BeginHorizontal();
EditorGUILayout.LabelField(new GUIContent("Deactivate After", "The time in seconds to automatically deactivate Destructible scripts when they are active and outside an ActivateDestructibles trigger area."), GUILayout.Width(100));
destManager.deactivateAfter = EditorGUILayout.FloatField(destManager.deactivateAfter, GUILayout.Width(30));
EditorGUILayout.LabelField("seconds", GUILayout.Width(50));
GUILayout.EndHorizontal();
}
EditorGUILayout.Separator();
EditorGUILayout.EndVertical();
EditorGUILayout.Separator();
base.OnInspectorGUI();
destManager.useCameraDistanceLimit = EditorGUILayout.Toggle(new GUIContent("Camera Distance Limit", "If true, destructible objects beyond the specified distance from the main camera will be destroyed in a more limiting (ie, higher performance) way, such as the fallback particle effect."), destManager.useCameraDistanceLimit);
if (destManager.useCameraDistanceLimit)
{
GUILayout.BeginHorizontal();
EditorGUILayout.LabelField("", GUILayout.Width(15));
destManager.cameraDistanceLimit = EditorGUILayout.IntField("If distance to camera >", destManager.cameraDistanceLimit);
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
EditorGUILayout.LabelField("", GUILayout.Width(15));
EditorGUILayout.LabelField("Limit destruction to", GUILayout.Width(100));
EditorGUILayout.EnumPopup(DestructionType.ParticleEffect);
GUILayout.EndHorizontal();
}
if (GUI.changed && !Application.isPlaying)
{
EditorUtility.SetDirty(destManager);
EditorSceneManager.MarkSceneDirty(SceneManager.GetActiveScene());
}
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 120e1ec105f1a6f4cac0103cb56cc8db
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,27 @@
using UnityEngine;
using UnityEditor;
namespace DestroyIt
{
public static class HideFlagsUtility
{
[MenuItem("Help/Hide Flags/Show All Objects")]
private static void ShowAll()
{
var allGameObjects = Object.FindObjectsOfType<GameObject>();
foreach (var go in allGameObjects)
{
switch (go.hideFlags)
{
case HideFlags.HideAndDontSave:
go.hideFlags = HideFlags.DontSave;
break;
case HideFlags.HideInHierarchy:
case HideFlags.HideInInspector:
go.hideFlags = HideFlags.None;
break;
}
}
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ca848dd29b36a224580037bc63c4f0ef
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,69 @@
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
namespace DestroyIt
{
[CustomEditor(typeof(HitEffects))]
public class HitEffectsEditor : Editor
{
private Texture deleteButton;
private HitEffects hitEffects;
public void OnEnable()
{
hitEffects = target as HitEffects;
deleteButton = Resources.Load("UI_Textures/delete-16x16") as Texture;
if (hitEffects.effects == null)
hitEffects.effects = new List<HitEffect>();
//Default to Everything mask
if (hitEffects.effects.Count == 0)
hitEffects.effects.Add(new HitEffect() {hitBy = (HitBy)(-1)}); // -1 == "Everything"
}
public override void OnInspectorGUI()
{
EditorGUILayout.BeginVertical("Box");
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("When hit by:", GUILayout.Width(100));
EditorGUILayout.LabelField("Use particle:", GUILayout.Width(100));
EditorGUILayout.EndHorizontal();
for (int i=0; i < hitEffects.effects.Count; i++)
{
HitEffect hitEffect = hitEffects.effects[i];
EditorGUILayout.BeginHorizontal();
hitEffect.hitBy = (HitBy) EditorGUILayout.EnumFlagsField(hitEffect.hitBy, GUILayout.Width(100));
hitEffect.effect = EditorGUILayout.ObjectField(hitEffect.effect, typeof(GameObject), false) as GameObject;
if (GUILayout.Button("-", GUILayout.Width(22)))
{
if (hitEffects.effects.Count > 1)
hitEffects.effects.Remove(hitEffect);
else
Debug.Log("Cannot remove the last remaining Hit Effect. Remove the script entirely if you don't want a hit effect to occur.");
}
EditorGUILayout.EndHorizontal();
}
// Add Button
EditorGUILayout.Separator();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("", GUILayout.Width(15));
if (GUILayout.Button("+", EditorStyles.toolbarButton, GUILayout.Width(30)))
hitEffects.effects.Add(new HitEffect() {hitBy = (HitBy)(-1)}); // Add the first available tag.
EditorGUILayout.EndHorizontal();
EditorGUILayout.Separator();
EditorGUILayout.EndVertical();
if (hitEffects != null && GUI.changed && !Application.isPlaying)
{
EditorUtility.SetDirty(hitEffects);
EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene());
}
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 233ea7235ad8f3d4dad38ad9e4afa12d
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,197 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.SceneManagement;
using Debug = UnityEngine.Debug;
namespace DestroyIt
{
[CustomEditor(typeof(ObjectPool))]
public class ObjectPoolEditor : Editor
{
private Texture deleteButton;
private Texture lockOff;
private Texture lockOn;
private readonly string[] delimiter = {":|:"}; // The complex delimiter for loading/saving Object Pool to file. Should be something you won't use in your prefab names.
private void OnEnable()
{
deleteButton = Resources.Load("UI_Textures/delete-16x16") as Texture;
lockOff = Resources.Load("UI_Textures/lock-off-16x16") as Texture;
lockOn = Resources.Load("UI_Textures/lock-on-16x16") as Texture;
}
public override void OnInspectorGUI()
{
ObjectPool objectPool = target as ObjectPool;
List<PoolEntry> changeEntries = new List<PoolEntry>();
if (objectPool != null && objectPool.prefabsToPool != null)
changeEntries = objectPool.prefabsToPool.ToList();
List<PoolEntry> removeEntries = new List<PoolEntry>();
GUIStyle style = new GUIStyle();
style.padding.top = 2;
if (changeEntries.Count > 0)
{
EditorGUILayout.LabelField("Prefab | Count | Pooled Only");
List<string> previouslyUsedNames = new List<string>();
foreach(PoolEntry entry in changeEntries)
{
// Remove duplicate entries
if (entry != null && entry.Prefab != null)
{
if (previouslyUsedNames.Contains(entry.Prefab.name))
{
Debug.LogWarning("Prefab \"" + entry.Prefab.name + "\" already exists in Object Pool (item #" + (previouslyUsedNames.IndexOf(entry.Prefab.name) + 1) + ").");
removeEntries.Add(entry);
continue;
}
previouslyUsedNames.Add(entry.Prefab.name);
}
EditorGUILayout.BeginHorizontal();
entry.Prefab = EditorGUILayout.ObjectField(entry.Prefab, typeof(GameObject), false) as GameObject;
entry.Count = EditorGUILayout.IntField(entry.Count, GUILayout.Width(20));
Texture currentLock = lockOff;
if (entry.OnlyPooled)
currentLock = lockOn;
if (GUILayout.Button(currentLock, style, GUILayout.Width(16)))
entry.OnlyPooled = !entry.OnlyPooled;
if (GUILayout.Button(deleteButton, style, GUILayout.Width(16)))
removeEntries.Add(entry); // flag for removal
EditorGUILayout.EndHorizontal();
}
// Remove entries flagged for removal
foreach (PoolEntry entry in removeEntries)
changeEntries.Remove(entry);
}
// Add entries button
EditorGUILayout.Separator();
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("+", EditorStyles.toolbarButton, GUILayout.Width(30)))
changeEntries.Add(new PoolEntry{ Prefab = null, Count = 1 });
EditorGUILayout.LabelField(" Add a prefab to the pool.");
EditorGUILayout.EndHorizontal();
EditorGUILayout.Separator();
// Suppress Warnings checkbox
EditorGUILayout.BeginHorizontal();
objectPool.suppressWarnings = EditorGUILayout.Toggle(objectPool.suppressWarnings, GUILayout.Width(16));
EditorGUILayout.LabelField("Suppress Warnings");
EditorGUILayout.EndHorizontal();
EditorGUILayout.Separator();
// IMPORT from file
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("Import", EditorStyles.toolbarButton, GUILayout.Width(70)))
{
string path = EditorUtility.OpenFilePanel("Import Object Pool Save File", SceneManager.GetActiveScene().path.SceneFolder(), "txt");
if (path.Length != 0 && File.Exists(path))
{
string[] lines = File.ReadAllLines(path);
if (EditorUtility.DisplayDialog("Add Items to Object Pool?", "Are you sure you want to import " + lines.Length + " items into the Object Pool from " + Path.GetFileName(path) + "?", "Add Items", "Cancel"))
{
int itemsModified = 0;
int itemsAdded = 0;
for (int i = 0; i < lines.Length; i++)
{
string[] parts = lines[i].Split(delimiter, StringSplitOptions.None);
string assetPath = AssetDatabase.GUIDToAssetPath(parts[1]);
GameObject prefab = AssetDatabase.LoadAssetAtPath(assetPath, typeof(GameObject)) as GameObject;
if (prefab == null)
{
Debug.LogWarning("Could not find \"" + parts[0] + "\" prefab.");
continue;
}
int count = Convert.ToInt32(parts[2]);
bool onlyPooled = Convert.ToBoolean(parts[3]);
PoolEntry existingEntry = changeEntries.Find(x => x.Prefab == prefab);
// Update existing entries
if (existingEntry != null)
{
bool updatedExisting = false;
if (existingEntry.Count < count)
{
existingEntry.Count = count;
updatedExisting = true;
}
if (onlyPooled && !existingEntry.OnlyPooled)
{
existingEntry.OnlyPooled = onlyPooled;
updatedExisting = true;
}
if (updatedExisting)
itemsModified++;
}
else // Add new entries
{
changeEntries.Add(new PoolEntry { Prefab = prefab, Count = count, OnlyPooled = onlyPooled });
itemsAdded++;
}
}
Debug.Log(String.Format("{0} imported into Object Pool. Results: {1} new items added, {2} existing items updated.", Path.GetFileName(path), itemsAdded, itemsModified));
}
}
}
// CLEAR object pool
EditorGUILayout.Space();
if (GUILayout.Button("Clear", EditorStyles.toolbarButton, GUILayout.Width(70)) &&
EditorUtility.DisplayDialog("Clear Object Pool?", "Are you sure you want to remove all objects from the object pool?", "Clear", "Cancel"))
{
changeEntries = new List<PoolEntry>();
Debug.Log("Object Pool cleared.");
}
// SAVE to file
EditorGUILayout.Space();
if (GUILayout.Button("Save", EditorStyles.toolbarButton, GUILayout.Width(70)))
{
string saveFilePath = EditorUtility.SaveFilePanel("Save Object File To", SceneManager.GetActiveScene().path.SceneFolder(), SceneManager.GetActiveScene().name.Replace(" ", "") + "ObjectPool.txt", "txt");
//string saveFilePath = SceneManager.GetActiveScene().path.SceneFolder() + "/ObjectPool-SaveFile.txt"; //"Assets/DestroyIt - Core/ObjectPool-SaveFile.txt";
if (saveFilePath.Length != 0)
{
if (objectPool.prefabsToPool != null && objectPool.prefabsToPool.Count > 0)
{
string[] lines = new string[objectPool.prefabsToPool.Count];
for (int i = 0; i < objectPool.prefabsToPool.Count; i++)
{
string assetPath = AssetDatabase.GetAssetPath(objectPool.prefabsToPool[i].Prefab.GetInstanceID());
string assetId = AssetDatabase.AssetPathToGUID(assetPath);
lines[i] = String.Format("{1}{0}{2}{0}{3}{0}{4}", string.Join("", delimiter), objectPool.prefabsToPool[i].Prefab.name, assetId, objectPool.prefabsToPool[i].Count, objectPool.prefabsToPool[i].OnlyPooled);
}
File.WriteAllLines(saveFilePath, lines);
Debug.Log(lines.Length + " object Pool entries saved to: " + saveFilePath + ".");
}
else
Debug.Log("Object Pool is empty. Nothing to save.");
}
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.Separator();
// Save changes back to object pool
objectPool.prefabsToPool = changeEntries;
if (GUI.changed && !Application.isPlaying)
{
EditorUtility.SetDirty(objectPool);
EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene());
}
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: bd1cc9aa7ce8b4f439692723e3eca90c
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,57 @@
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace DestroyIt
{
public class SetupDestroyIt
{
[MenuItem("Window/DestroyIt/Setup - Minimal")]
public static void SetupMinimalMenuOption()
{
GameObject destroyIt;
DestructionManager destructionManager = Object.FindObjectOfType<DestructionManager>();
if (destructionManager != null)
destroyIt = destructionManager.gameObject;
else
destroyIt = new GameObject("DestroyIt");
destroyIt.AddComponent<DestructionManager>();
destroyIt.AddComponent<ParticleManager>();
ObjectPool pool = destroyIt.AddComponent<ObjectPool>();
DestructionTest destructionTest = Object.FindObjectOfType<DestructionTest>();
if (destructionTest == null)
{
GameObject destroyItTest = new GameObject("DestroyIt-InputTest");
destroyItTest.AddComponent<DestructionTest>();
}
if (pool != null)
{
GameObject defaultLargeParticle = Resources.Load<GameObject>("Default_Particles/DefaultLargeParticle");
GameObject defaultSmallParticle = Resources.Load<GameObject>("Default_Particles/DefaultSmallParticle");
pool.prefabsToPool = new List<PoolEntry>();
pool.prefabsToPool.Add(new PoolEntry() {Count = 10, Prefab = defaultLargeParticle});
pool.prefabsToPool.Add(new PoolEntry() {Count = 10, Prefab = defaultSmallParticle});
}
}
[MenuItem("Window/DestroyIt/Setup - Destructible Trees")]
public static void SetupDestructibleTreesMenuOption()
{
EditorUtility.DisplayDialog("A Note About Destructible Trees",
"NOTE: You will need to uncheck Enable Tree Colliders on your terrain in order to use destructible trees.\n\n" +
"Once you've added your trees to the terrain, click the \"Update Trees\" button on the TreeManager, and DestroyIt will " +
"create game objects with colliders and place them over the terrain tree instances so they can be destroyed.", "Ok");
DestructionManager destructionManager = Object.FindObjectOfType<DestructionManager>();
if (destructionManager == null)
SetupMinimalMenuOption();
destructionManager = Object.FindObjectOfType<DestructionManager>();
destructionManager.gameObject.AddComponent<TreeManager>();
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 7611c01637181174a99747067e7f7b60
timeCreated: 1427418461
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,38 @@
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace DestroyIt
{
[CustomEditor(typeof(StructuralSupport))]
public class StructuralSupportEditor : Editor
{
public override void OnInspectorGUI()
{
StructuralSupport strSupport = target as StructuralSupport;
base.OnInspectorGUI();
EditorGUILayout.Separator();
if (GUILayout.Button("Add Supports", GUILayout.Width(170)))
{
strSupport.AddStructuralSupport();
}
if (GUILayout.Button("Remove Supports", GUILayout.Width(170)))
{
strSupport.RemoveStructuralSupport();
}
EditorGUILayout.Separator();
if (GUI.changed && !Application.isPlaying)
{
EditorUtility.SetDirty(strSupport);
EditorSceneManager.MarkSceneDirty(SceneManager.GetActiveScene());
}
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: f0e430181e61d0649a789afd5df5455a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,120 @@
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.SceneManagement;
// ReSharper disable InconsistentNaming
namespace DestroyIt
{
[CustomEditor(typeof(TagIt))]
public class TagItEditor : Editor
{
private Texture deleteButton;
private TagIt tagIt;
public void OnEnable()
{
tagIt = target as TagIt;
deleteButton = Resources.Load("UI_Textures/delete-16x16") as Texture;
if (tagIt.tags == null)
tagIt.tags = new List<Tag>();
if (tagIt.tags.Count == 0)
tagIt.tags.Add(Tag.Untagged);
}
public override void OnInspectorGUI()
{
string removeTagName = "";
Tag changeTagFrom = Tag.Untagged;
Tag changeTagTo = Tag.Untagged;
List<string> tagOptions;
GUIStyle style = new GUIStyle();
style.padding.top = 2;
EditorGUILayout.BeginVertical("Box");
EditorGUILayout.LabelField("Tags on this game object:");
foreach(Tag tag in tagIt.tags)
{
// Reset the list of tag options for each tag.
tagOptions = Enum.GetNames(typeof(Tag)).ToList();
tagOptions.Sort();
// Remove the other tags this object already has.
foreach (Tag t in tagIt.tags)
{
if (t == tag) continue; // don't remove the current tag.
tagOptions.Remove(Enum.GetName(typeof(Tag), t));
}
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("", GUILayout.Width(15));
// get the selected option
int selectedIndex = tagOptions.IndexOf(Enum.GetName(typeof(Tag), tag));
selectedIndex = EditorGUILayout.Popup(selectedIndex,tagOptions.ToArray());
Tag newTag = (Tag)Enum.Parse(typeof(Tag), tagOptions[selectedIndex]);
if (tag != newTag)
{
changeTagFrom = tag;
changeTagTo = newTag;
}
if (GUILayout.Button(deleteButton, style, GUILayout.Width(16)))
removeTagName = tagOptions[selectedIndex]; // flag for removal
EditorGUILayout.EndHorizontal();
}
// Change tag (if neccessary).
if (changeTagFrom != changeTagTo)
{
int idx = tagIt.tags.IndexOf(changeTagFrom);
tagIt.tags[idx] = changeTagTo;
}
// Remove selected tag (if any).
if (tagIt.tags.Count > 1 && removeTagName != "")
{
Tag removeTag = (Tag)Enum.Parse(typeof(Tag), removeTagName);
tagIt.tags.Remove(removeTag);
}
else if (tagIt.tags.Count == 1 && removeTagName != "") // if we are removing the last item, just remove the TagIt script.
DestroyImmediate(tagIt.gameObject.GetComponent<TagIt>());
// Add/Remove Buttons
tagOptions = Enum.GetNames(typeof(Tag)).ToList();
tagOptions.Sort();
List<string> usedTags = new List<string>();
foreach(Tag tag in tagIt.tags)
usedTags.Add(Enum.GetName(typeof(Tag), tag));
usedTags.Sort();
bool showAddButton = tagIt.tags.Count < tagOptions.Count;
if (showAddButton)
{
EditorGUILayout.Separator();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("", GUILayout.Width(15));
if (GUILayout.Button("+", EditorStyles.toolbarButton, GUILayout.Width(30)))
{
tagOptions.RemoveAll(x => usedTags.Contains(x));
Tag firstAvailableTag = (Tag)Enum.Parse(typeof(Tag), tagOptions[0]);
tagIt.tags.Add(firstAvailableTag); // Add the first available tag.
}
EditorGUILayout.EndHorizontal();
}
EditorGUILayout.Separator();
EditorGUILayout.EndVertical();
if (tagIt != null && GUI.changed && !Application.isPlaying)
{
EditorUtility.SetDirty(tagIt);
EditorSceneManager.MarkSceneDirty(SceneManager.GetActiveScene());
}
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: a842fef0415669f47bce3a9c4b29df80
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,31 @@
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace DestroyIt
{
[CustomEditor(typeof(TreeManager))]
public class TreeManagerEditor : Editor
{
public override void OnInspectorGUI()
{
TreeManager treeManager = target as TreeManager;
base.OnInspectorGUI();
EditorGUILayout.Separator();
if (GUILayout.Button("Update Trees", EditorStyles.toolbarButton, GUILayout.Width(160)))
TreeManager.Instance.UpdateTrees();
EditorGUILayout.Separator();
if (GUI.changed && !Application.isPlaying)
{
EditorUtility.SetDirty(treeManager);
EditorSceneManager.MarkSceneDirty(SceneManager.GetActiveScene());
}
}
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 466b6db7016e4b36a47cf5d2159bec6c
timeCreated: 1530589652

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: db5bc5d4abc0963409e6fbea1189ccbd
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: f3a99b6d396c32a4eb2a3f34dc6a99b0
folderAsset: yes
timeCreated: 1427397479
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,49 @@
using UnityEngine;
// ReSharper disable IdentifierTypo
namespace DestroyIt
{
public class ActivateDestructibles : MonoBehaviour
{
private DestructionManager _destructionManager;
private void Start()
{
_destructionManager = DestructionManager.Instance;
if (_destructionManager == null)
{
Debug.LogError("DestructionManager could not be found or created in the scene. Removing script.");
Destroy(this);
}
}
private void OnTriggerEnter(Collider other)
{
// Ignore Player objects
if (other.gameObject.CompareTag("Player")) return;
Destructible destructible = other.gameObject.GetComponentInParent<Destructible>();
if (destructible == null) return;
if (destructible.isTerrainTree && _destructionManager.destructibleTreesStayDeactivated) return;
if (!destructible.enabled)
destructible.enabled = true;
}
private void OnTriggerExit(Collider other)
{
// Ignore Player objects
if (other.gameObject.CompareTag("Player")) return;
Destructible destructible = other.gameObject.GetComponentInParent<Destructible>();
if (destructible == null) return;
if (destructible.enabled && !destructible.isTerrainTree && _destructionManager.autoDeactivateDestructibles) // deactivate non-terrain trees
destructible.shouldDeactivate = true;
else if (destructible.enabled && destructible.isTerrainTree && _destructionManager.autoDeactivateDestructibleTerrainObjects) // deactivate terrain trees
destructible.shouldDeactivate = true;
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: a3678786273380f499d192333f4cc2a0
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,46 @@
using UnityEngine;
namespace DestroyIt
{
public class AutoDamage : MonoBehaviour
{
public int startAtHitPoints = 30;
public float damageIntervalSeconds = 0.5f;
public int damagePerInterval = 5;
private bool _isInitialized;
private Destructible _destructible;
private bool _autoDamageStarted;
void Start()
{
_destructible = gameObject.GetComponent<Destructible>();
if (_destructible == null)
{
Debug.LogWarning("No Destructible object found! AutoDamage removed.");
Destroy(this);
}
_isInitialized = true;
}
void Update()
{
if (!_isInitialized) return;
if (_destructible == null) return;
if (_autoDamageStarted) return;
if (_destructible.CurrentHitPoints <= startAtHitPoints)
{
InvokeRepeating("ApplyDamage", 0f, damageIntervalSeconds);
_autoDamageStarted = true;
}
}
void ApplyDamage()
{
if (_destructible == null) return;
_destructible.ApplyDamage(damagePerInterval);
}
}
}

View File

@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: a497b0926a01c584086140c092748bd6
timeCreated: 1526789610
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,126 @@
using System.Collections.Generic;
using UnityEngine;
// ReSharper disable ForCanBeConvertedToForeach
// ReSharper disable CommentTypo
// ReSharper disable IdentifierTypo
namespace DestroyIt
{
[RequireComponent(typeof(Destructible))]
[RequireComponent(typeof(Rigidbody))]
public class ChainDestruction : MonoBehaviour
{
[Tooltip("The amount of damage to apply per second to adjacent Destructible objects in the destructible chain. This will control how fast objects are destroyed.")]
public float damagePerSecond = 125f;
[Tooltip("If you would like to apply force on the debris pieces from a specific position point, you can assign a specific Transform location for that here. If you leave this empty, the gameObject's position will be used as the force origin point.")]
public Transform forcePosition;
[Tooltip("The amount of force to apply to the debris pieces (if any) when they are destroyed.")]
public float forceAmount = 300f;
[Tooltip("The size in game units (usually meters) of the force radius. A larger force radius will make debris pieces (if any) fly farther away from the force origin point.")]
public float forceRadius = 5f;
[Tooltip("The amount of upward push exerted on the debris pieces (if any). More upward push can make the force look more interesting or cinematic, but too much (say, over 2) can be unrealistic.")]
public float forceUpwardModifier;
[HideInInspector]
public List<Destructible> adjacentDestructibles; // This is a list of adjacent Destructible objects, ones overlapping the trigger collider of this object.
[Tooltip("Set to TRUE to cause this Destructible object to start taking damage at the predefined damage rate (Damage Per Second).")]
public bool destroySelf;
private Destructible _destObj; // Reference to the Destructible component on this gameObject.
private void Start()
{
adjacentDestructibles = new List<Destructible>();
// Attempt to get the Destructible script on the object. If found, attach the OnDestroyed event listener to the DestroyedEvent.
_destObj = gameObject.GetComponent<Destructible>();
if (_destObj != null)
_destObj.DestroyedEvent += OnDestroyed;
if (!HasTriggerCollider())
Debug.LogWarning("No trigger collider found on ChainDestruction gameObject. You need a trigger collider for this script to work properly.");
}
private void Update()
{
if (!destroySelf) return;
if (damagePerSecond > 0f)
{
// If you don't care about adding force to the debris pieces, uncomment this code to use a simpler method of applying damage.
//destObj.ApplyDamage(damagePerSecond * Time.fixedDeltaTime);
//return;
// Apply damage with force on the debris pieces.
Damage damage = new ExplosiveDamage()
{
DamageAmount = damagePerSecond * Time.deltaTime,
BlastForce = forceAmount,
Position = forcePosition != null ? forcePosition.position : transform.position,
Radius = forceRadius,
UpwardModifier = forceUpwardModifier
};
_destObj.ApplyDamage(damage);
}
}
private void OnDisable()
{
// Unregister the event listener when disabled/destroyed. Very important to prevent memory leaks due to orphaned event listeners!
if (_destObj == null) return;
_destObj.DestroyedEvent -= OnDestroyed;
}
/// <summary>When this Destructible object is destroyed, the code in this method will run.</summary>
private void OnDestroyed()
{
if (adjacentDestructibles == null || adjacentDestructibles.Count == 0) return;
// For each adjacent Destructible object, set DestroySelf to true for its ChainDestruction component, so it will start taking damage.
for (int i = 0; i < adjacentDestructibles.Count; i++)
{
Destructible adjacentDest = adjacentDestructibles[i];
if (adjacentDest == null) continue;
ChainDestruction chainDest = adjacentDest.gameObject.GetComponent<ChainDestruction>();
if (chainDest == null) continue;
chainDest.destroySelf = true;
}
}
private void OnTriggerEnter(Collider other)
{
// Add the nearby item to the list of adjacent Destructibles.
var otherDestObj = other.gameObject.GetComponentInParent<Destructible>();
if (otherDestObj != null && !adjacentDestructibles.Contains(otherDestObj))
adjacentDestructibles.Add(otherDestObj);
}
private void OnTriggerExit(Collider other)
{
// Remove the item that is no longer nearby from the list of adjacent Destructibles.
var otherDestObj = other.gameObject.GetComponentInParent<Destructible>();
if (otherDestObj != null && adjacentDestructibles.Contains(otherDestObj))
adjacentDestructibles.Remove(otherDestObj);
}
/// <summary>Returns True if there is a trigger collider on this game object. Otherwise, returns False.</summary>
private bool HasTriggerCollider()
{
Collider[] colls = gameObject.GetComponents<Collider>();
if (colls == null) return false;
for (int i = 0; i < colls.Length; i++)
{
if (colls[i].isTrigger)
return true;
}
return false;
}
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: df192195518b4f4f97306fa8b5758eb9
timeCreated: 1548308591

View File

@@ -0,0 +1,52 @@
using UnityEngine;
// ReSharper disable ForCanBeConvertedToForeach
// ReSharper disable IdentifierTypo
// ReSharper disable LoopCanBeConvertedToQuery
// ReSharper disable CommentTypo
namespace DestroyIt
{
/// <summary>
/// This script triggers a chain destruction sequence on one or more Destructible objects that also have the
/// ChainDestruction component. Put this script on a trigger collider and assign one or more Destructible
/// objects that have the ChainDestruction component to the ChainDestructions collection.
/// </summary>
[RequireComponent(typeof(Collider))]
public class ChainDestructionTrigger : MonoBehaviour
{
public ChainDestruction[] chainDestructions;
private void Start()
{
if (!HasTriggerCollider())
Debug.LogWarning("No trigger collider found on ChainDestructionTrigger gameObject. You need a trigger collider for this script to work properly.");
}
private void OnTriggerEnter(Collider other)
{
if (chainDestructions == null || chainDestructions.Length == 0) return;
// For each ChainDestruction component to trigger, set its destroySelf flag to True.
for (int i = 0; i < chainDestructions.Length; i++)
{
if (chainDestructions[i] == null) continue;
chainDestructions[i].destroySelf = true;
}
}
/// <summary>Returns True if there is a trigger collider on this game object. Otherwise, returns False.</summary>
private bool HasTriggerCollider()
{
Collider[] colls = gameObject.GetComponents<Collider>();
if (colls == null) return false;
for (int i = 0; i < colls.Length; i++)
{
if (colls[i].isTrigger)
return true;
}
return false;
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 383dc81c4944a0e44949828cbc7d186c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,77 @@
using UnityEngine;
// ReSharper disable CommentTypo
// ReSharper disable IdentifierTypo
namespace DestroyIt
{
/// <summary>
/// This script is attached to a debris piece at runtime. Your projectiles should check for collisions with
/// ChipAwayDebris and fire the BreakOff() method when impact occurs.
/// </summary>
public class ChipAwayDebris : MonoBehaviour
{
public float debrisMass = 1f;
public float debrisDrag = 0f;
public float debrisAngularDrag = 0.05f;
private Renderer _rend;
public void BreakOff(Vector3 force, Vector3 point)
{
if (!CheckCanBreakOff()) return;
// Check whether a rigidbody already exists
Rigidbody existingRBody = _rend.gameObject.GetComponent<Rigidbody>();
Rigidbody rbody;
// Make the debris fall away by attaching a rigidbody to it.
rbody = existingRBody == null ? _rend.gameObject.AddComponent<Rigidbody>() : existingRBody;
rbody.mass = debrisMass;
rbody.drag = debrisDrag;
rbody.angularDrag = debrisAngularDrag;
rbody.AddForceAtPosition(force, point, ForceMode.Impulse);
rbody.gameObject.transform.SetParent(null);
Destroy(this);
}
public void BreakOff(float blastForce, float explosionRadius, float upwardsModifier)
{
if (!CheckCanBreakOff()) return;
//Debug.Log("Breaking off");
// Make the debris fall away by attaching a rigidbody to it.
Rigidbody rbody = _rend.gameObject.AddComponent<Rigidbody>();
rbody.mass = debrisMass;
rbody.drag = debrisDrag;
rbody.angularDrag = debrisAngularDrag;
rbody.AddExplosionForce(blastForce, transform.position, explosionRadius, upwardsModifier);
Destroy(this);
}
private bool CheckCanBreakOff()
{
// If no collider is on this object, then something weird happened. Exit and destroy self.
if (GetComponent<Collider>() == null)
{
Destroy(this);
return false;
}
_rend = gameObject.GetComponentInParent<Renderer>();
if (_rend == null)
{
Destroy(this);
return false;
}
// If a rigidbody already exists on this debris piece, remove this script and exit.
if (GetComponent<Collider>().attachedRigidbody != null)
{
Destroy(this);
return false;
}
return true;
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 21475ccb6d09a1e4bbd5cd92987edc19
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,16 @@
using UnityEngine;
namespace DestroyIt
{
public class ClingPoint : MonoBehaviour
{
public int chanceToCling = 75;
private void OnDrawGizmos()
{
Gizmos.color = Color.yellow;
Gizmos.DrawWireSphere(this.transform.position - (this.transform.forward * 0.025f), .01f);
Gizmos.DrawRay(this.transform.position - (this.transform.forward * 0.025f), this.transform.forward * 0.075f);
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 3f5b9e5a44e24a04c85b856c6bdec6d1
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,45 @@
using UnityEngine;
namespace DestroyIt
{
/// <summary>
/// This script is used to add a Rigidbody component to a gameobject through code. It allows you to start with an object that has no Rigidbody
/// and add one at a later time by calling Initialize() on this script. The script deletes itself after adding the Rigidbody.
/// </summary>
public class DelayedRigidbody : MonoBehaviour
{
public float mass = 1f;
public float drag = 0f;
public float angularDrag = 0.05f;
public float delaySeconds = 0f;
public bool reenableColliders = true;
/// <summary>This is called whenever you want to add a rigidbody to the game object.</summary>
public void Initialize()
{
Invoke("AddRigidbody", delaySeconds);
}
public void AddRigidbody()
{
// Add a rigidbody component if it doesn't already exist.
if (gameObject.GetComponent<Rigidbody>() == null)
{
Rigidbody rbody = gameObject.AddComponent<Rigidbody>();
rbody.mass = mass;
rbody.drag = drag;
rbody.angularDrag = angularDrag;
}
if (reenableColliders)
{
Collider[] colliders = gameObject.GetComponentsInChildren<Collider>();
foreach(Collider coll in colliders)
coll.enabled = true;
}
// Deletes this script when finished.
Destroy(this);
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: a2817944056bc0b47a421eadf80faab3
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,32 @@
using UnityEngine;
namespace DestroyIt
{
/// <summary>This script will destroy the gameobject it is attached to after [seconds].</summary>
public class DestroyAfter : MonoBehaviour
{
public float seconds; // seconds to wait before destroying this game object.
private float timeLeft;
private bool isInitialized;
void Start()
{
timeLeft = seconds;
isInitialized = true;
}
void OnEnable()
{
timeLeft = seconds;
}
void Update()
{
if (!isInitialized) return;
timeLeft -= Time.deltaTime;
if (timeLeft <= 0)
Destroy(this.gameObject);
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: de08e9a9bd37ed844b649cf29d176a6c
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,70 @@
using System;
using UnityEngine;
using Random = UnityEngine.Random;
namespace DestroyIt
{
/// <summary>
/// Put this script on a game object in your scene, and it will destroy Destructible object when you press the associated key.
/// </summary>
public class DestroyOnKeypress : MonoBehaviour
{
public float force = 500f;
public float radius = 10f;
public float upwardModifier = -1;
public ObjectToDestroy[] objectsToDestroy;
void Update()
{
// Look for keys that may have been pressed.
for (int i = 0; i < objectsToDestroy.Length; i++)
{
if (string.IsNullOrEmpty(objectsToDestroy[i].key)) continue;
// Get the keycode for each keypress we want to look for
KeyCode key = (KeyCode)Enum.Parse(typeof(KeyCode), objectsToDestroy[i].key.ToUpper());
// If the keypress matches the keycode configured, try to destroy the destructible objects assigned to it
if (Input.GetKeyUp(key))
{
// For each destructible object assigned to this keycode...
Destructible[] destObjs = objectsToDestroy[i].destructibles;
for (int j = 0; j < destObjs.Length; j++)
{
if (destObjs[j] == null) continue;
// If there is a collider on the destructible object, capture the tallest point on the collider. We'll use it to apply force so the object won't be stationary once destroyed.
Collider coll = destObjs[j].GetComponentInChildren<Collider>();
if (coll != null)
{
Vector3 pos = destObjs[j].transform.position;
Vector3 tallestPoint = coll.ClosestPoint(new Vector3(pos.x, pos.y+5000f, pos.z));
// Apply the force to a random offset spot around the tallest point of the collider. This will make it so the force is a little unpredictable.
float randomX = Random.Range(1, 4);
if (Random.Range(0, 2) == 1) randomX *= -1;
float randomZ = Random.Range(1, 4);
if (Random.Range(0, 2) == 1) randomZ *= -1;
Vector3 forcePoint = new Vector3(tallestPoint.x + randomX, tallestPoint.y, tallestPoint.z + randomZ);
// Apply the damage, with random force added
destObjs[j].ApplyDamage(new ExplosiveDamage {
BlastForce = force, DamageAmount = destObjs[j].CurrentHitPoints + 1,
Position = forcePoint, Radius = radius, UpwardModifier = upwardModifier
});
}
else // If there is no collider on the Destructible object, just destroy it
destObjs[j].Destroy();
}
}
}
}
}
[Serializable]
public class ObjectToDestroy
{
public string key;
public Destructible[] destructibles;
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: fe486b865324dee46aed1f765abb5950
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,483 @@
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Serialization;
// ReSharper disable ArrangeAccessorOwnerBody
// ReSharper disable UnusedMember.Global
// ReSharper disable ForCanBeConvertedToForeach
namespace DestroyIt
{
/// <summary>Put this script on an object you want to be destructible.</summary>
[DisallowMultipleComponent]
public class Destructible : MonoBehaviour
{
public float TotalHitPoints
{
get { return _totalHitPoints; }
set
{
_totalHitPoints = value;
damageLevels.CalculateDamageLevels(_totalHitPoints);
}
}
public float CurrentHitPoints
{
get { return _currentHitPoints; }
set { _currentHitPoints = value; }
}
[SerializeField]
[FormerlySerializedAs("totalHitPoints")]
[HideInInspector]
private float _totalHitPoints = 50f;
[SerializeField]
[FormerlySerializedAs("currentHitPoints")]
[HideInInspector]
private float _currentHitPoints = 50f;
[HideInInspector] public List<DamageLevel> damageLevels;
[HideInInspector] public GameObject destroyedPrefab;
[HideInInspector] public GameObject destroyedPrefabParent;
[HideInInspector] public ParticleSystem fallbackParticle;
[HideInInspector] public int fallbackParticleMatOption;
[HideInInspector] public List<DamageEffect> damageEffects;
[HideInInspector] public float velocityReduction = .5f;
[HideInInspector] public bool limitDamage = false;
[HideInInspector] public float minDamage = 10f; // The minimum amount of damage the object can receive per hit.
[HideInInspector] public float maxDamage = 100f; // The maximum amount of damage the object can receive per hit.
[HideInInspector] public float minDamageTime = 0f; // The minimum amount of time (in seconds) that must pass before the object can be damaged again.
[HideInInspector] public float ignoreCollisionsUnder = 2f;
[HideInInspector] public List<GameObject> unparentOnDestroy;
[HideInInspector] public bool disableKinematicOnUparentedChildren = true;
[HideInInspector] public List<MaterialMapping> replaceMaterials;
[HideInInspector] public List<MaterialMapping> replaceParticleMats;
[HideInInspector] public bool canBeDestroyed = true;
[HideInInspector] public bool canBeRepaired = true;
[HideInInspector] public List<string> debrisToReParentByName;
[HideInInspector] public bool debrisToReParentIsKinematic;
[HideInInspector] public List<string> childrenToReParentByName;
[HideInInspector] public bool isDebrisChipAway;
[HideInInspector] public float chipAwayDebrisMass = 1f;
[HideInInspector] public float chipAwayDebrisDrag;
[HideInInspector] public float chipAwayDebrisAngularDrag = 0.05f;
[HideInInspector] public bool autoPoolDestroyedPrefab = true;
[HideInInspector] public bool useFallbackParticle = true;
[HideInInspector] public Vector3 centerPointOverride;
[HideInInspector] public Vector3 fallbackParticleScale = Vector3.one;
[HideInInspector] public Transform fallbackParticleParent;
[HideInInspector] public bool sinkWhenDestroyed;
[HideInInspector] public bool shouldDeactivate; // If true, this script will deactivate after a set period of time (configurable on DestructionManager).
[HideInInspector] public bool isTerrainTree; // Is this Destructible object a stand-in for a terrain tree?
[HideInInspector] public AudioClip destroyedSound;
[HideInInspector] public AudioClip damagedSound;
[HideInInspector] public AudioClip repairedSound;
// Private variables
private const float InvulnerableTimer = 0.5f; // How long (in seconds) the destructible object is invulnerable after instantiation.
private DamageLevel _currentDamageLevel;
private bool _isInitialized;
private float _deactivateTimer;
private bool _firstFixedUpdate = true;
private Rigidbody _rigidBody; // store a reference to this destructible object's rigidbody, so we don't have to use GetComponent() at runtime.
private bool _isInvulnerable; // Determines whether the destructible object starts with a short period of invulnerability. Prevents destructible debris being immediately destroyed by the same forces that destroyed the original object.
// Properties
public bool UseProgressiveDamage { get; set; } = true; // Used to determine if the shader on the destructible object is
public bool CheckForClingingDebris { get; set; } = true; // This is an added optimization used when we are auto-pooling destroyed prefabs. It allows us to avoid a GetComponentsInChildren() check for ClingPoints destruction time.
public Rigidbody[] PooledRigidbodies { get; set; } // This is an added optimization used when we are auto-pooling destroyed prefabs. It allows us to avoid multiple GetComponentsInChildren() checks for Rigidbodies at destruction time.
public GameObject[] PooledRigidbodyGos { get; set; } // This is an added optimization used when we are auto-pooling destroyed prefabs. It allows us to avoid multiple GetComponentsInChildren() checks for the GameObjects on Rigidibodies at destruction time.
public float VelocityReduction => Mathf.Abs(velocityReduction - 1f) /* invert the velocity reduction value (so it makes sense in the UI) */;
public Quaternion RotationFixedUpdate { get; private set; }
public Vector3 PositionFixedUpdate { get; private set; }
public Vector3 VelocityFixedUpdate { get; private set; }
public Vector3 AngularVelocityFixedUpdate { get; private set; }
public float LastRepairedAmount { get; private set; }
public float LastDamagedAmount { get; private set; }
public float LastDamagedTime { get; private set; }
public bool IsDestroyed => !_isInvulnerable && canBeDestroyed && CurrentHitPoints <= 0;
public Vector3 MeshCenterPoint { get; private set; }
// Events
public event Action DamagedEvent;
public event Action DestroyedEvent;
public event Action RepairedEvent;
public void Start()
{
CheckForClingingDebris = true;
if (damageLevels == null || damageLevels.Count == 0)
damageLevels = DestructibleHelper.DefaultDamageLevels();
damageLevels.CalculateDamageLevels(TotalHitPoints);
// Store a reference to this object's rigidbody, for better performance.
_rigidBody = GetComponent<Rigidbody>();
// Only calculate the mesh center point if the destructible object uses a fallback particle.
if (useFallbackParticle)
{
MeshRenderer[] meshRenderers = gameObject.GetComponentsInChildren<MeshRenderer>();
MeshCenterPoint = gameObject.GetMeshCenterPoint(meshRenderers);
if (gameObject.IsAnyMeshPartOfStaticBatch(meshRenderers) && centerPointOverride == Vector3.zero)
Debug.Log($"[{gameObject.name}] is a Destructible object with one or more static meshes, but no position override for the fallback particle effect. Particle effect may not spawn where you expect.");
}
PlayDamageEffects();
_isInvulnerable = true;
Invoke(nameof(RemoveInvulnerability), InvulnerableTimer);
if (gameObject.HasTagInParent(Tag.TerrainTree))
isTerrainTree = true;
// If AutoPool is turned on, add the destroyed prefab to the ObjectPool.
if (autoPoolDestroyedPrefab)
ObjectPool.Instance.AddDestructibleObjectToPool(this);
_isInitialized = true;
}
public void RemoveInvulnerability()
{
_isInvulnerable = false;
}
public void FixedUpdate()
{
if (!_isInitialized) return;
DestructionManager destructionManager = DestructionManager.Instance;
if (destructionManager == null) return;
// Use the fixed update position/rotation for placement of the destroyed prefab.
PositionFixedUpdate = transform.position;
RotationFixedUpdate = transform.rotation;
if (_rigidBody != null)
{
VelocityFixedUpdate = _rigidBody.velocity;
AngularVelocityFixedUpdate = _rigidBody.angularVelocity;
}
SetDamageLevel();
PlayDamageEffects();
// Check if this script should be auto-deactivated, as configured on the DestructionManager
if (destructionManager.autoDeactivateDestructibles && !isTerrainTree && shouldDeactivate)
UpdateDeactivation(destructionManager.deactivateAfter);
else if (destructionManager.autoDeactivateDestructibleTerrainObjects && isTerrainTree && shouldDeactivate)
UpdateDeactivation(destructionManager.deactivateAfter);
if (IsDestroyed)
destructionManager.ProcessDestruction(this, destroyedPrefab, new ExplosiveDamage());
// If this is the first fixed update frame and autoDeativateDestructibles is true, start this component deactivated.
if (_firstFixedUpdate)
this.SetActiveOrInactive(destructionManager);
_firstFixedUpdate = false;
}
private void UpdateDeactivation(float deactivateAfter)
{
if (_deactivateTimer > deactivateAfter)
{
_deactivateTimer = 0f;
shouldDeactivate = false;
enabled = false;
}
else
_deactivateTimer += Time.fixedDeltaTime;
}
/// <summary>Applies a generic amount of damage, with no specific impact or explosive force.</summary>
public void ApplyDamage(float amount)
{
if (IsDestroyed || _isInvulnerable || !DestructionManager.Instance.allowDamage) return; // don't try to apply damage to an already-destroyed or invulnerable object, or if damaging object is not allowed.
// Adjust the damage based on Min/Max/Time thresholds.
if (limitDamage)
{
if (LastDamagedTime > 0f && minDamageTime > 0f && Time.time < LastDamagedTime + minDamageTime)
return;
if (maxDamage >= 0 && amount > maxDamage)
amount = maxDamage;
if (minDamage >= 0 && minDamage <= maxDamage && amount < minDamage)
amount = minDamage;
if (amount <= 0) return;
}
LastDamagedAmount = amount;
LastDamagedTime = Time.time;
FireDamagedEvent();
// Check for any audio clip we may need to play
if (damagedSound != null)
AudioSource.PlayClipAtPoint(damagedSound, transform.position);
CurrentHitPoints -= amount;
if (CurrentHitPoints > 0) return;
if (CurrentHitPoints < 0) CurrentHitPoints = 0;
PlayDamageEffects();
if (IsDestroyed)
DestructionManager.Instance.ProcessDestruction(this, destroyedPrefab, new DirectDamage{DamageAmount = amount});
}
public void ApplyDamage(Damage damage)
{
if (IsDestroyed || _isInvulnerable || !DestructionManager.Instance.allowDamage) return; // don't try to apply damage to an already-destroyed or invulnerable object, or if damaging object is not allowed.
// Adjust the damage based on Min/Max/Time thresholds.
if (limitDamage)
{
if (LastDamagedTime > 0f && minDamageTime > 0f && Time.time < LastDamagedTime + minDamageTime)
return;
if (maxDamage >= 0 && damage.DamageAmount > maxDamage)
damage.DamageAmount = maxDamage;
if (minDamage >= 0 && minDamage <= maxDamage && damage.DamageAmount < minDamage)
damage.DamageAmount = minDamage;
if (damage.DamageAmount <= 0) return;
}
LastDamagedAmount = damage.DamageAmount;
LastDamagedTime = Time.time;
FireDamagedEvent();
// Check for any audio clip we may need to play
if (damagedSound != null)
AudioSource.PlayClipAtPoint(damagedSound, transform.position);
CurrentHitPoints -= damage.DamageAmount;
if (CurrentHitPoints > 0) return;
if (CurrentHitPoints < 0) CurrentHitPoints = 0;
PlayDamageEffects();
if (IsDestroyed)
DestructionManager.Instance.ProcessDestruction(this, destroyedPrefab, damage);
}
public void RepairDamage(float amount)
{
if (IsDestroyed || !canBeRepaired) return; // object cannot be repaired if it is either already destroyed or not repairable.
LastRepairedAmount = amount;
CurrentHitPoints += amount;
if (CurrentHitPoints > TotalHitPoints) // object cannot be over-repaired beyond its total hit points.
CurrentHitPoints = TotalHitPoints;
PlayDamageEffects();
FireRepairedEvent();
// Check for any audio clip we may need to play
if (repairedSound != null)
AudioSource.PlayClipAtPoint(repairedSound, transform.position);
}
public void Destroy()
{
if (IsDestroyed || _isInvulnerable) return; // don't try to destroy an already-destroyed or invulnerable object.
LastDamagedAmount = CurrentHitPoints;
LastDamagedTime = Time.time;
FireDamagedEvent();
CurrentHitPoints = 0;
PlayDamageEffects();
DestructionManager.Instance.ProcessDestruction(this, destroyedPrefab, CurrentHitPoints);
}
/// <summary>Advances the damage state, applies damage-level materials as needed, and plays particle effects.</summary>
private void SetDamageLevel()
{
DamageLevel damageLevel = damageLevels?.GetDamageLevel(CurrentHitPoints);
if (damageLevel == null) return;
if (_currentDamageLevel != null && damageLevel == _currentDamageLevel) return;
_currentDamageLevel = damageLevel;
Renderer[] renderers = GetComponentsInChildren<Renderer>();
foreach (Renderer rend in renderers)
{
Destructible parentDestructible = rend.GetComponentInParent<Destructible>(); // child Destructible objects should not be affected by damage on their parents.
if (parentDestructible != this) continue;
bool isAcceptableRenderer = rend is MeshRenderer || rend is SkinnedMeshRenderer;
if (isAcceptableRenderer && !rend.gameObject.HasTag(Tag.ClingingDebris) && rend.gameObject.layer != DestructionManager.Instance.debrisLayer)
{
for (int j = 0; j < rend.sharedMaterials.Length; j++)
DestructionManager.Instance.SetProgressiveDamageTexture(rend, rend.sharedMaterials[j], _currentDamageLevel);
}
}
PlayDamageEffects();
}
/// <summary>Gets the material to use for the fallback particle effect when this Destructible object is destroyed.</summary>
public Material GetDestroyedParticleEffectMaterial()
{
Renderer[] renderers = GetComponentsInChildren<Renderer>();
foreach (Renderer rend in renderers)
{
Destructible parentDestructible = rend.GetComponentInParent<Destructible>(); // only get the material for the parent object to use for a particle effect
if (parentDestructible != this) continue;
bool isAcceptableRenderer = rend is MeshRenderer || rend is SkinnedMeshRenderer;
if (isAcceptableRenderer)
return rend.sharedMaterial;
}
return null; // could not find an acceptable material to use for particle effects
}
private void PlayDamageEffects()
{
// Check if we should play a particle effect for this damage level
if (damageEffects == null || damageEffects.Count == 0) return;
int currentDamageLevelIndex = 0;
if (_currentDamageLevel != null)
currentDamageLevelIndex = damageLevels.IndexOf(_currentDamageLevel); // FindIndex(a => a == currentDamageLevel);
foreach (DamageEffect effect in damageEffects)
{
if (effect == null || effect.Prefab == null) continue;
// Get rotation
Quaternion rotation = transform.rotation;
if (effect.Rotation != Vector3.zero)
rotation = transform.rotation * Quaternion.Euler(effect.Rotation);
// Is this effect only played if the destructible object has a certain tag?
if (effect.HasTagDependency && !gameObject.HasTag(effect.TagDependency))
continue;
if (_currentDamageLevel != null && effect.TriggeredAt < damageLevels.Count)
{
// TURN ON pre-destruction damage effects
if (currentDamageLevelIndex >= effect.TriggeredAt && !effect.HasStarted)
{
if (effect.GameObject != null)
{
for (int i = 0; i < effect.ParticleSystems.Length; i++)
{
ParticleSystem.EmissionModule emission = effect.ParticleSystems[i].emission;
emission.enabled = true;
}
}
else
{
// set parent to this destructible object and play
effect.GameObject = ObjectPool.Instance.Spawn(effect.Prefab, effect.Offset, rotation, transform);
if (effect.GameObject != null)
{
effect.ParticleSystems = effect.GameObject.GetComponentsInChildren<ParticleSystem>();
if (effect.Scale != Vector3.one)
{
foreach (ParticleSystem ps in effect.ParticleSystems)
{
var main = ps.main;
main.scalingMode = ParticleSystemScalingMode.Hierarchy;
}
effect.GameObject.transform.localScale = effect.Scale;
}
}
}
effect.HasStarted = true;
}
// TURN OFF pre-destruction damage effects
if (currentDamageLevelIndex < effect.TriggeredAt && effect.HasStarted)
{
if (effect.GameObject != null)
{
for (int i = 0; i < effect.ParticleSystems.Length; i++)
{
ParticleSystem.EmissionModule emission = effect.ParticleSystems[i].emission;
emission.enabled = false;
}
}
effect.HasStarted = false;
}
}
// Destroyed effects
if (effect.TriggeredAt == damageLevels.Count && IsDestroyed && !effect.HasStarted)
{
effect.GameObject = canBeDestroyed ?
ObjectPool.Instance.Spawn(effect.Prefab, transform.TransformPoint(effect.Offset), rotation) :
ObjectPool.Instance.Spawn(effect.Prefab, effect.Offset, rotation, transform);
if (effect.GameObject != null)
{
effect.ParticleSystems = effect.GameObject.GetComponentsInChildren<ParticleSystem>();
if (effect.Scale != Vector3.one)
{
foreach (ParticleSystem ps in effect.ParticleSystems)
{
var main = ps.main;
main.scalingMode = ParticleSystemScalingMode.Hierarchy;
}
effect.GameObject.transform.localScale = effect.Scale;
}
}
effect.HasStarted = true;
}
}
}
// NOTE: OnCollisionEnter will only fire if a rigidbody is attached to this object!
public void OnCollisionEnter(Collision collision)
{
if (DestructionManager.Instance == null) return;
if (!isActiveAndEnabled) return;
this.ProcessDestructibleCollision(collision, GetComponent<Rigidbody>());
if (collision.contacts.Length <= 0) return;
Destructible destructibleObj = collision.contacts[0].otherCollider.gameObject.GetComponentInParent<Destructible>();
if (destructibleObj != null && collision.contacts[0].otherCollider.attachedRigidbody == null)
destructibleObj.ProcessDestructibleCollision(collision, GetComponent<Rigidbody>());
}
// NOTE: OnDrawGizmos will only fire if Gizmos are turned on in the Unity Editor!
public void OnDrawGizmos()
{
damageEffects.DrawGizmos(transform);
centerPointOverride.DrawGizmos(transform);
}
public void FireDestroyedEvent()
{
DestroyedEvent?.Invoke(); // If there is at least one listener, trigger the event.
}
public void FireRepairedEvent()
{
RepairedEvent?.Invoke(); // If there is at least one listener, trigger the event.
}
public void FireDamagedEvent()
{
DamagedEvent?.Invoke(); // If there is at least one listener, trigger the event.
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: b1bbb502083c41048a8fedc6a9693be7
timeCreated: 1426551760
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {fileID: 2800000, guid: d4098816c8eb6084296c44408c9fa393, type: 3}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,26 @@
using UnityEngine;
namespace DestroyIt
{
/// <summary>
/// Place this script on a rigidbody parent that has one or more compound collider Destructible children under it.
/// Example: the SUV in the showcase demo scene. It is a rigidbody parent but not Destructible itself. But it has many child colliders that are destructible objects.
/// </summary>
public class DestructibleParent : MonoBehaviour
{
private void OnCollisionEnter(Collision collision)
{
if (collision.contacts.Length == 0) return;
Destructible destructibleObj = collision.contacts[0].thisCollider.gameObject.GetComponentInParent<Destructible>();
if (destructibleObj != null)
{
Rigidbody otherRbody = collision.contacts[0].otherCollider.attachedRigidbody;
if (otherRbody != null)
destructibleObj.ProcessDestructibleCollision(collision, otherRbody);
else
destructibleObj.ProcessDestructibleCollision(collision, this.GetComponent<Rigidbody>());
}
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 8abcb0608c0a3654f97e7a38649246e3
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,30 @@
using UnityEngine;
namespace DestroyIt
{
/// <summary>
/// This script applies damage to all destructible objects in the scene every time you press the "0" key.
/// This script is for testing purposes.
/// </summary>
[DisallowMultipleComponent]
public class DestructionTest : MonoBehaviour
{
public Destructible objectToDestroy;
public int damagePerPress = 13; // The amount of damage to apply to all destructible objects per keypress.
public void Update()
{
if (Input.GetKeyUp("0"))
{
if (objectToDestroy != null)
objectToDestroy.ApplyDamage(damagePerPress);
else
{
Destructible[] destObjs = FindObjectsOfType<Destructible>();
foreach (Destructible destObj in destObjs)
destObj.ApplyDamage(damagePerPress);
}
}
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: dbcfca89a861f8846959fde873e9142f
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,41 @@
using UnityEngine;
namespace DestroyIt
{
/// <summary>
/// This script is used in conjunction with Object Pooling to enhance performance, in particular with mobile devices.
/// This script enables the colliders on a game object over a small amount of time, so the physics load on the CPU is spaced out.
/// </summary>
public class EnableColliderAfter : MonoBehaviour
{
public float seconds; // seconds to wait before enabling the collider on this game object.
private float timeLeft;
private bool isInitialized;
void Start()
{
timeLeft = seconds;
isInitialized = true;
}
void OnEnable()
{
timeLeft = seconds;
}
void Update()
{
if (!isInitialized) return;
timeLeft -= Time.deltaTime;
if (timeLeft <= 0)
{
Collider[] colliders = gameObject.GetComponents<Collider>();
for (int i = 0; i < colliders.Length; i++)
colliders[i].enabled = true;
Destroy(this);
}
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 755d107b7f868e84aa09e5429fc073eb
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,44 @@
using UnityEngine;
namespace DestroyIt
{
/// <summary>
/// This script is used in conjunction with Object Pooling to enhance performance, in particular with mobile devices.
/// This script enables gravity on a game object's rigidbody over a small amount of time, so the physics load on the CPU is spaced out.
/// </summary>
public class EnableGravityAfter : MonoBehaviour
{
public float seconds; // seconds to wait before enabling rigidbody gravity on this game object.
private float _timeLeft;
private bool _isInitialized;
void Start()
{
_timeLeft = seconds;
_isInitialized = true;
}
void OnEnable()
{
_timeLeft = seconds;
}
void Update()
{
if (!_isInitialized) return;
if (GetComponent<Rigidbody>() == null)
{
Destroy(this);
return;
}
_timeLeft -= Time.deltaTime;
if (_timeLeft <= 0)
{
GetComponent<Rigidbody>().useGravity = true;
Destroy(this);
}
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 3673fd21a2dbb574d90e88efd449af5f
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,41 @@
using UnityEngine;
namespace DestroyIt
{
/// <summary>This script will intantiate the specified explosion prefab after [seconds].</summary>
public class ExplodeAfter : MonoBehaviour
{
[Tooltip("Prefab to instantiate when time runs out.")]
public GameObject explosionPrefab;
[Tooltip("Seconds to wait before explosion.")]
public float seconds = 5f;
private float _timeLeft;
private bool _isInitialized;
public void Start()
{
_timeLeft = seconds;
_isInitialized = true;
}
public void OnEnable()
{
_timeLeft = seconds;
}
public void Update()
{
if (!_isInitialized) return;
_timeLeft -= Time.deltaTime;
if (_timeLeft <= 0)
{
if (explosionPrefab != null)
Instantiate(explosionPrefab, this.transform.position, Quaternion.identity);
Destroy(this.gameObject);
}
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: f82f41d034c9f744e9c7cd51b498250c
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,27 @@
using UnityEngine;
using System.Collections;
namespace DestroyIt
{
public class FlashingLight : MonoBehaviour
{
public float flashInterval = 0.5f;
private Light _flashingLight;
public void Start()
{
_flashingLight = GetComponent<Light>();
StartCoroutine(Flashing());
}
private IEnumerator Flashing()
{
while (true)
{
yield return new WaitForSeconds(flashInterval);
_flashingLight.enabled = !_flashingLight.enabled;
}
}
}
}

View File

@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 57eaebec4f1ef1d4a83ce16dca58b16d
timeCreated: 1525715169
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,27 @@
using System.Collections.Generic;
using UnityEngine;
namespace DestroyIt
{
/// <summary>
/// This script allows you to assign particle system hit effects for each weapon type.
/// PlayEffect() will attempt to play the hit effect for the specified weapon type.
/// </summary>
[DisallowMultipleComponent]
public class HitEffects : MonoBehaviour
{
public List<HitEffect> effects;
public void PlayEffect(HitBy weaponType, Vector3 hitPoint, Vector3 hitNormal)
{
foreach (var eff in effects)
{
if ((eff.hitBy & weaponType) > 0)
{
if (eff.effect != null)
ObjectPool.Instance.Spawn(eff.effect, hitPoint, Quaternion.LookRotation(hitNormal));
}
}
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 9ae5a7a1942384f45a292ce82d781740
timeCreated: 1485105957
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,51 @@
using UnityEngine;
namespace DestroyIt
{
public class PoolAfter : MonoBehaviour
{
public float seconds; // seconds to wait before re-pooling this game object.
public bool reenableChildren; // determines whether to re-enable all child objects when this object is pooled.
public bool removeWhenPooled; // Remove this script when the object is pooled?
public bool resetToPrefab; // Reset the entire object back to prefab? (This means it will destroy and recreate the object.)
private float _timeLeft;
private bool _isInitialized;
void Start()
{
_timeLeft = seconds;
_isInitialized = true;
}
void OnEnable()
{
_timeLeft = seconds;
}
void Update()
{
if (!_isInitialized) return;
_timeLeft -= Time.deltaTime;
if (_timeLeft <= 0)
{
if (resetToPrefab)
{
GameObject objectToPool = ObjectPool.Instance.SpawnFromOriginal(this.gameObject.name);
if (objectToPool != null)
ObjectPool.Instance.PoolObject(objectToPool);
Destroy(this.gameObject);
_isInitialized = false;
return;
}
if (removeWhenPooled)
Destroy(this);
ObjectPool.Instance.PoolObject(this.gameObject, reenableChildren);
}
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 2173075f949abe34cbac509d346178e1
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,42 @@
using UnityEngine;
namespace DestroyIt
{
public class ReleaseObject : MonoBehaviour
{
public GameObject objectToRelease;
public Vector3 angularVelocity;
public Vector3 forceToAdd;
private Vector3 _velocityLastUpdate;
void Start()
{
_velocityLastUpdate = GetComponent<Rigidbody>().velocity;
}
void FixedUpdate()
{
Vector3 velocityChange = (GetComponent<Rigidbody>().velocity - _velocityLastUpdate) / GetComponent<Rigidbody>().mass;
if (velocityChange.magnitude > .3f && objectToRelease != null)
Release();
}
void OnCollisionEnter(Collision collision)
{
if (collision.relativeVelocity.magnitude > 2f && objectToRelease != null)
Release();
}
private void Release()
{
objectToRelease.GetComponent<Rigidbody>().isKinematic = false;
objectToRelease.GetComponent<Rigidbody>().angularVelocity = angularVelocity;
objectToRelease.GetComponent<Rigidbody>().WakeUp();
if (forceToAdd != Vector3.zero)
objectToRelease.GetComponent<Rigidbody>().AddForce(forceToAdd);
Destroy(this);
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: d828c710697789a48952b008bae74122
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,32 @@
using UnityEngine;
namespace DestroyIt
{
/// <summary>
/// This script is used for directly spawning objects into the scene from the Object Pool.
/// Simply place this script on an empty gameobject at the same location/rotation you would normally instantiate your prefab.
/// Useful for spawning particle effects on destroyed objects.
/// </summary>
public class SpawnObject : MonoBehaviour
{
[Tooltip("The prefab of the object you want to spawn into the scene from the object pool.")]
public GameObject prefab;
private ObjectPool _objectPool;
private void Start()
{
_objectPool = ObjectPool.Instance;
if (_objectPool == null)
{
Debug.LogWarning("Object Pool was not found or could not be created. Removing script and exiting.");
Destroy(this);
return;
}
_objectPool.Spawn(prefab, transform.localPosition, transform.localRotation, transform.parent);
gameObject.SetActive(false);
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 7cbf7229232d1914f9693032f370f1cd
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,158 @@
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
// ReSharper disable once InlineOutVariableDeclaration
namespace DestroyIt
{
/// <summary>
/// Put this script on a destroyed object that has debris pieces you want to stay connected together with joints. (Note: if the object is a prefab, unpack it first.)
/// The joints this script creates will give your destroyed object's debris pieces structural support until they are destroyed or knocked off by force.
/// </summary>
public class StructuralSupport : MonoBehaviour
{
[Tooltip("This is the maximum distance allowed to make a structural support connection. Reduce it if you're getting pieces that float in the air and defy physics. Increase it if too many pieces aren't connecting when they should be.")]
public float maxConnectionDistance = 1.25f;
[Tooltip("The force required to break a joint on the structure. Set to -1 for Infinity.")]
public float breakForce = 1250f;
[Tooltip("The torque required to break a joint on the structure. Set to -1 for Infinity.")]
public float breakTorque = 3000f;
private class StructuralPiece
{
public GameObject GameObject { get; set; }
public Rigidbody Rigidbody { get; set; }
public Vector3 CenterPoint { get; set; }
}
public void FixedUpdate()
{
// Inspect all the joints during every physics loop and remove any that have missing connected rigidbodies
FixedJoint[] joints = gameObject.GetComponentsInChildren<FixedJoint>();
bool jointsRemoved = false;
for (int i = 0; i < joints.Length; i++)
{
if (joints[i].connectedBody == null)
{
Destroy(joints[i]); // remove the joint
jointsRemoved = true;
}
}
// If any joints were removed, wake up the rigidbodies on the object
if (jointsRemoved)
{
Rigidbody[] rbodies = gameObject.GetComponentsInChildren<Rigidbody>();
foreach (Rigidbody rbody in rbodies)
rbody.WakeUp();
}
}
[ExecuteInEditMode]
public void AddStructuralSupport()
{
#if UNITY_EDITOR
List<StructuralPiece> pieces = new List<StructuralPiece>();
List<StructuralPiece> otherPieces = new List<StructuralPiece>();
// First, get a list of all rigidbodies on the object
List<Rigidbody> rbodies = gameObject.GetComponentsInChildren<Rigidbody>().ToList();
// Clear off any old joints on the object so we can create new joint connections.
foreach (var comp in gameObject.GetComponentsInChildren<Component>())
{
if (comp is Joint)
DestroyImmediate(comp);
}
// Next, get the mesh centerpoint of each rigidbody's game object
foreach (Rigidbody rbody in rbodies)
{
Vector3 center = Vector3.zero;
foreach (Collider coll in rbody.gameObject.GetComponentsInChildren<Collider>())
center = center != Vector3.zero ? Vector3.Lerp(center, coll.bounds.center, 0.5f) : coll.bounds.center;
pieces.Add(new StructuralPiece {
GameObject = rbody.gameObject,
Rigidbody = rbody,
CenterPoint = center
});
otherPieces.Add(new StructuralPiece {
GameObject = rbody.gameObject,
Rigidbody = rbody,
CenterPoint = center
});
}
// Now, for each piece, try to linecast from the center of it to the center of every other piece.
foreach (StructuralPiece piece in pieces)
{
for (int i = 0; i < otherPieces.Count; i++)
{
// skip if this piece is trying to linecast to itself.
if (piece.GameObject.GetInstanceID() == otherPieces[i].GameObject.GetInstanceID()) continue;
// If the connection distance is farther than our threshold will allow, exit.
if (Vector3.Distance(piece.CenterPoint, otherPieces[i].CenterPoint) > maxConnectionDistance) continue;
// Capture the layer this object is on, and move it to the IgnoreRaycast layer temporarily before doing the linecast, so it ignores itself.
int originalLayer = piece.GameObject.layer;
int ignoreLayer = LayerMask.NameToLayer("Ignore Raycast");
piece.GameObject.SetLayerRecursively(ignoreLayer);
// If we hit a collider while linecasting to the other piece, check it and see if it IS the other piece. If so, that means it's adjacent, and we want to attach a joint connecting the two.
RaycastHit hitInfo;
if (Physics.Linecast(piece.CenterPoint, otherPieces[i].CenterPoint, out hitInfo))
{
if (hitInfo.collider.attachedRigidbody == otherPieces[i].Rigidbody)
{
//Debug.Log($"{piece.GameObject.name} is connected to {otherPieces[i].GameObject.name}");
for (int j=0; j<8; j++)
Debug.DrawLine(piece.CenterPoint, otherPieces[i].CenterPoint, Color.green, 10f);
Vector3 midPoint = Vector3.Lerp(piece.CenterPoint, otherPieces[i].CenterPoint, 0.5f);
if (breakForce <= -0.1f)
breakForce = Single.PositiveInfinity;
if (breakTorque <= -0.1f)
breakTorque = Single.PositiveInfinity;
piece.GameObject.AddStiffJoint(otherPieces[i].Rigidbody, midPoint, Vector3.zero, breakForce, breakTorque);
}
}
// Set the layer on the piece back to what it was originally
piece.GameObject.SetLayerRecursively(originalLayer);
}
// Remove this piece from the "other pieces" to check
otherPieces.RemoveAll(x => x.GameObject.GetInstanceID() == piece.GameObject.GetInstanceID());
}
#endif
}
[ExecuteInEditMode]
public void RemoveStructuralSupport()
{
#if UNITY_EDITOR
FixedJoint[] joints = gameObject.GetComponentsInChildren<FixedJoint>();
for (int i = 0; i < joints.Length; i++)
DestroyImmediate(joints[i]); // remove the joint
#endif
}
}
public static class LayerExtensions
{
public static void SetLayerRecursively(this GameObject obj, int layer)
{
obj.layer = layer;
foreach (Transform child in obj.transform)
child.gameObject.SetLayerRecursively(layer);
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 7da473fd710ae3e4ea5a6bfed246029a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,68 @@
using UnityEngine;
namespace DestroyIt
{
/// <summary>
/// This script manages a single support point (a Trigger Collider) on an object.
/// On startup, if the support point is connected to another rigidbody, it will create a custom joint connecting the two.
/// </summary>
public class SupportPoint : MonoBehaviour
{
public int breakForce = 750;
public int breakTorque = 750;
private bool _canSupport = true;
void Start()
{
if (transform.parent == null)
{
Debug.Log("[" + name + "] has no parent. Support points are designed to be children of objects that have attached colliders.");
_canSupport = false;
}
else if (transform.parent.GetComponent<Collider>() == null || !transform.parent.GetComponent<Collider>().enabled)
{
Debug.Log("[" + transform.parent.name + "] has a support point but no enabled collider. Support points only work on objects with colliders.");
_canSupport = false;
}
else if (transform.parent.GetComponent<Collider>().attachedRigidbody == null)
{
Debug.Log("[" + transform.parent.name + "] has a support point but no attached rigidbody. Support points only work on objects with rigidbodies.");
_canSupport = false;
}
if (_canSupport)
{
Ray ray = new Ray(transform.position - (transform.forward * 0.025f), transform.forward); // need to start the ray behind the transform a little
//Debug.DrawRay(this.transform.position, this.transform.forward * .15f, Color.red, 10f);
RaycastHit[] hitInfo = Physics.RaycastAll(ray, 0.075f);
for(int i=0; i<hitInfo.Length; i++)
{
// ignore colliders without rigidbodies to attach a joint to.
if (hitInfo[i].collider.attachedRigidbody == null) continue;
// ignore other trigger colliders - we only want to attach to the parent object.
if (hitInfo[i].collider.isTrigger) continue;
// Get the forward angle, as it relates to the parent
Vector3 angleAxis = transform.parent.transform.InverseTransformDirection(transform.TransformDirection(Vector3.forward));
// Add a stiff joint for support.
transform.parent.GetComponent<Collider>().attachedRigidbody.gameObject.AddStiffJoint(hitInfo[i].collider.attachedRigidbody,
transform.localPosition, angleAxis, breakForce, breakTorque);
break;
}
}
Destroy(gameObject);
}
private void OnDrawGizmos()
{
Gizmos.color = Color.yellow;
Gizmos.DrawWireSphere(transform.position - (transform.forward * 0.025f), .01f);
Gizmos.DrawRay(transform.position - (transform.forward * 0.025f), transform.forward * 0.075f);
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: d131f47680139ef448bbf60c9da110a8
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,44 @@
using UnityEngine;
namespace DestroyIt
{
/// <summary>
/// This script tags all colliders on the object after X seconds. It is used to tag colliders on destroyed object
/// debris with minimal performance impact.
/// </summary>
public class TagAfter : MonoBehaviour
{
public float seconds = 1f; // seconds to wait before tagging all colliders under this game object.
public Tag tagWith; // what to tag all colliders under this game object with.
private float _timeLeft;
private bool _isInitialized;
void Start()
{
_timeLeft = seconds;
_isInitialized = true;
}
void OnEnable()
{
_timeLeft = seconds;
}
void Update()
{
if (!_isInitialized) return;
_timeLeft -= Time.deltaTime;
if (_timeLeft <= 0)
{
Collider[] colls = this.gameObject.GetComponentsInChildren<Collider>();
for (int i = 0; i < colls.Length; i++)
colls[i].gameObject.AddTag(tagWith);
Destroy(this);
}
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 4153d7ec8f83d1a448229ed26f28814a
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,26 @@
using UnityEngine;
using System.Collections.Generic;
// ReSharper disable InconsistentNaming
namespace DestroyIt
{
/// <summary>
/// TagIt is a system that allows you to mark objects with multiple tags. It is used by DestroyIt to keep track of debris,
/// destructible groups, cling points, etc.
/// If you are using TagIt to specify hit effects on a destructible object, you should use the HitEffects script instead.
/// </summary>
[DisallowMultipleComponent]
public class TagIt : MonoBehaviour
{
public List<Tag> tags;
public void OnEnable()
{
if (tags == null)
tags = new List<Tag>();
if (tags.Count == 0)
tags.Add(Tag.Untagged);
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: d3dbf5a679affaa4f8cdc6a7adcd4e4b
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,62 @@
using UnityEditor;
using UnityEngine;
namespace DestroyIt
{
[ExecuteInEditMode]
[DisallowMultipleComponent]
public class TerrainPreserver : MonoBehaviour
{
public void Awake ()
{
#if UNITY_EDITOR
if (Application.isPlaying) return;
// Get the terrain to try to preserve.
TreeManager treeManager = gameObject.GetComponent<TreeManager>();
if (treeManager == null) return;
Terrain terrain = treeManager.terrain;
if (terrain == null)
terrain = Terrain.activeTerrain;
if (terrain == null) return;
// Check to see if a terrainData backup exists.
string terrainDataPath = AssetDatabase.GetAssetPath(terrain.terrainData);
string terrainDataBkpPath = terrainDataPath.Replace(".asset", "") + "_bkp.asset";
TerrainData terrainDataBkp = AssetDatabase.LoadAssetAtPath<TerrainData>(terrainDataBkpPath);
// If a terrainData backup exists, ask the user if they want to restore tree data from the backup.
if (terrainDataBkp != null)
{
int option = EditorUtility.DisplayDialogComplex("Restore Terrain Trees from Backup?",
"The Unity Editor may not have shut down correctly last time, which could mean destructible terrain trees were removed from terrain [" + terrain.terrainData.name + "]. Fortunately, there is a backup.\n\n" +
"Choose 'Restore' to restore trees from the backup. Choose 'Don't Restore' to keep existing trees as they are " +
"and delete the backup. Choose 'Ask Later' to do nothing right now, so you can inspect your terrain and make the decision later.",
"Restore", "Ask Later", "Don't Restore");
switch (option)
{
// Restore trees from backup
case 0:
terrain.terrainData.treeInstances = terrainDataBkp.treeInstances;
AssetDatabase.DeleteAsset(terrainDataBkpPath);
Debug.Log("Tree instances restored on [" + terrain.terrainData.name + "].");
break;
// Don't do anything - the user will be prompted again next time this script runs
case 1:
break;
// Don't restore trees and delete backup
case 2:
AssetDatabase.DeleteAsset(terrainDataBkpPath);
break;
default:
Debug.LogError("Unrecognized option.");
break;
}
}
#endif
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 33d5c334120e92b46b6b3d17525d6e80
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,35 @@
using UnityEngine;
namespace DestroyIt
{
/// <summary>
/// This is a helper script that listens to a Destructible object's DamagedEvent and runs additional code when the object is damaged.
/// Put this script on a GameObject that has the Destructible script.
/// </summary>
[RequireComponent(typeof(Destructible))]
public class WhenDamaged : MonoBehaviour
{
private Destructible _destObj;
private void Start()
{
// Try to get the Destructible script on the object. If found, attach the OnDamaged event listener to the DamagedEvent.
_destObj = gameObject.GetComponent<Destructible>();
if (_destObj != null)
_destObj.DamagedEvent += OnDamaged;
}
private void OnDisable()
{
// Unregister the event listener when disabled/destroyed. Very important to prevent memory leaks due to orphaned event listeners!
if (_destObj == null) return;
_destObj.DamagedEvent -= OnDamaged;
}
/// <summary>When the Destructible object is damaged, the code in this method will run.</summary>
private void OnDamaged()
{
Debug.Log($"{_destObj.name} was damaged for {_destObj.LastDamagedAmount} hit points");
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 34ffae2eac105914e83a47dd47709e7d
timeCreated: 1480569302
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,43 @@
using UnityEngine;
namespace DestroyIt
{
/// <summary>
/// Put this script on a GameObject that has the Destructible script.
/// When this object is damaged, it will also apply that damage to all of its parent Destructible objects.
/// </summary>
[RequireComponent(typeof(Destructible))]
public class WhenDamagedDamageParents : MonoBehaviour
{
private Destructible _destObj;
private void Start()
{
// Try to get the Destructible script on the object. If found, attach the OnDamaged event listener to the DamagedEvent.
_destObj = gameObject.GetComponent<Destructible>();
if (_destObj != null)
_destObj.DamagedEvent += OnDamaged;
}
private void OnDisable()
{
// Unregister the event listener when disabled/destroyed. Very important to prevent memory leaks due to orphaned event listeners!
if (_destObj == null) return;
_destObj.DamagedEvent -= OnDamaged;
}
/// <summary>When the Destructible object is damaged, the code in this method will run.</summary>
private void OnDamaged()
{
// Get a reference to all the Destructible parents of this object
Destructible[] destructibleParents = gameObject.GetComponentsInParent<Destructible>();
// Loop through the destructible parent objects and apply damage
for (int i = 0; i < destructibleParents.Length; i++)
{
if (destructibleParents[i] == _destObj) continue; // Ignore the current destructible object
destructibleParents[i].ApplyDamage(_destObj.LastDamagedAmount); // Apply the damage to only parent objects
}
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 3a49aec3c54ac8344acb427b9a830442
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,35 @@
using UnityEngine;
namespace DestroyIt
{
/// <summary>
/// This is a helper script that listens to a Destructible object's DestroyedEvent and runs additional code when the object is destroyed.
/// Put this script on a GameObject that has the Destructible script.
/// </summary>
[RequireComponent(typeof(Destructible))]
public class WhenDestroyed : MonoBehaviour
{
private Destructible _destObj;
private void Start()
{
// Try to get the Destructible script on the object. If found, attach the OnDestroyed event listener to the DestroyedEvent.
_destObj = gameObject.GetComponent<Destructible>();
if (_destObj != null)
_destObj.DestroyedEvent += OnDestroyed;
}
private void OnDisable()
{
// Unregister the event listener when disabled/destroyed. Very important to prevent memory leaks due to orphaned event listeners!
if (_destObj == null) return;
_destObj.DestroyedEvent -= OnDestroyed;
}
/// <summary>When the Destructible object is destroyed, the code in this method will run.</summary>
private void OnDestroyed()
{
Debug.Log($"{_destObj.name} was destroyed at world coordinates: {_destObj.transform.position}");
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: ec03d957467764141969df91f9a37fcc
timeCreated: 1461724580
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,41 @@
using UnityEngine;
namespace DestroyIt
{
/// <summary>
/// This is a helper script that listens to a Destructible object's DestroyedEvent and plays a sound when the object is destroyed.
/// Put this script on a GameObject that has the Destructible script.
/// </summary>
public class WhenDestroyedPlaySound : MonoBehaviour
{
public AudioClip clip;
private Destructible _destObj;
private void Start()
{
// Try to get the Destructible script on the object. If found, attach the OnDestroyed event listener to the DestroyedEvent.
_destObj = gameObject.GetComponent<Destructible>();
if (_destObj != null)
_destObj.DestroyedEvent += OnDestroyed;
}
private void OnDisable()
{
// Unregister the event listener when disabled/destroyed. Very important to prevent memory leaks due to orphaned event listeners!
if (_destObj == null) return;
_destObj.DestroyedEvent -= OnDestroyed;
}
/// <summary>When the Destructible object is destroyed, the code in this method will run.</summary>
private void OnDestroyed()
{
// Create a new game object to play the audio clip, and position it at the destroyed game object's location.
var audioObj = new GameObject("Audio Source");
audioObj.transform.position = _destObj.transform.position;
var audioSource = audioObj.AddComponent<AudioSource>();
var destroyAfter = audioObj.AddComponent<DestroyAfter>();
destroyAfter.seconds = 5f; // Destroy the audio source object after X seconds.
audioSource.PlayOneShot(clip); // Play the audio clip.
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: dc8c9d2635bcc244b8a6753462da6f74
timeCreated: 1463421045
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,49 @@
using System;
using UnityEngine;
namespace DestroyIt
{
/// <summary>
/// This is a helper script that listens to a Destructible object's DestroyedEvent and runs additional code when the object is destroyed.
/// Put this script on a GameObject that has the Destructible script.
/// </summary>
[RequireComponent(typeof(Destructible))]
public class WhenDestroyedResetTree : MonoBehaviour
{
[Tooltip("How many seconds to wait before resetting the tree.")]
public float resetAfterSeconds = 30f;
private Destructible _destObj;
private void Start()
{
// Try to get the Destructible script on the object. If found, attach the OnDestroyed event listener to the DestroyedEvent.
_destObj = gameObject.GetComponent<Destructible>();
if (_destObj != null)
_destObj.DestroyedEvent += OnDestroyed;
}
private void OnDisable()
{
// Unregister the event listener when disabled/destroyed. Very important to prevent memory leaks due to orphaned event listeners!
if (_destObj == null) return;
_destObj.DestroyedEvent -= OnDestroyed;
}
/// <summary>When the Destructible object is destroyed, the code in this method will run.</summary>
private void OnDestroyed()
{
Debug.Log($"{_destObj.name} was destroyed at world coordinates: {_destObj.transform.position}");
TerrainTree terrainTree = Terrain.activeTerrain.ClosestTreeToPoint(transform.position);
TreeReset tree = new TreeReset()
{
prototypeIndex = terrainTree.TreeInstance.prototypeIndex,
position = terrainTree.TreeInstance.position,
color = terrainTree.TreeInstance.color,
heightScale = terrainTree.TreeInstance.heightScale,
widthScale = terrainTree.TreeInstance.widthScale,
resetTime = DateTime.Now.AddSeconds(resetAfterSeconds)
};
TreeManager.Instance.treesToReset.Add(tree);
}
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 2c2ddca75a0e4e2e9a76326cb378bb42
timeCreated: 1549237993

View File

@@ -0,0 +1,35 @@
using UnityEngine;
namespace DestroyIt
{
/// <summary>
/// This is a helper script that listens to a Destructible object's RepairedEvent and runs additional code when the object is repaired.
/// Put this script on a GameObject that has the Destructible script.
/// </summary>
[RequireComponent(typeof(Destructible))]
public class WhenRepaired : MonoBehaviour
{
private Destructible _destObj;
private void Start()
{
// Try to get the Destructible script on the object. If found, attach the OnRepaired event listener to the RepairedEvent.
_destObj = gameObject.GetComponent<Destructible>();
if (_destObj != null)
_destObj.RepairedEvent += OnRepaired;
}
private void OnDisable()
{
// Unregister the event listener when disabled/destroyed. Very important to prevent memory leaks due to orphaned event listeners!
if (_destObj == null) return;
_destObj.RepairedEvent -= OnRepaired;
}
/// <summary>When the Destructible object is repaired, the code in this method will run.</summary>
private void OnRepaired()
{
Debug.Log($"{_destObj.name} was repaired {_destObj.LastRepairedAmount} hit points");
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 3b10107f86c0c6543a3256ef38b80d00
timeCreated: 1476058790
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,3 @@
{
"name": "Destroy.Runtime"
}

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 3a5d3214f3d7fb845bf8991981763e58
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,17 @@
fileFormatVersion: 2
guid: 46b9e9b3a1e926c4eac2be881a4c08e6
labels:
- Destruction
- Destroy
- Physics
- DestroyIt
- Damage
- Fracturing
- Demolition
folderAsset: yes
timeCreated: 1427397479
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,39 @@
using System;
namespace DestroyIt
{
public static class ArrayExtensions
{
/// <summary>Provides a quick way to remove elements from a standard array.</summary>
public static T[] RemoveAllAt<T>(this T[] array, int[] removeIndices)
{
T[] newArray = new T[0];
if (removeIndices.Length == 0) return array;
if (removeIndices.Length >= array.Length) return newArray;
newArray = new T[array.Length];
int i = 0;
int j = 0;
int itemsKept = 0;
while (i < array.Length)
{
bool keepItem = true;
for (int x = 0; x < removeIndices.Length; x++)
{
if (i == removeIndices[x])
keepItem = false;
}
if (keepItem)
{
itemsKept++;
newArray[j] = array[i];
j++;
}
i++;
}
Array.Resize(ref newArray, itemsKept);
return newArray;
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: bbde6c1a812a73349864180510448026
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,233 @@
using System.Collections.Generic;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor.SceneManagement;
#endif
// ReSharper disable ForCanBeConvertedToForeach
namespace DestroyIt
{
public static class DestructionExtensions
{
public static void Update(this List<float> models, int withinSeconds)
{
bool isChanged = false;
if (models.Count > 0)
{
for (int i = 0; i < models.Count; i++)
{
if (Time.time > (models[i] + withinSeconds))
{
models.Remove(models[i]);
isChanged = true;
}
}
if (isChanged)
DestructionManager.Instance.FireDestroyedPrefabCounterChangedEvent();
}
}
public static void ReleaseClingingDebris(this Destructible destroyedObj)
{
List<Transform> clingingDebris = new List<Transform>();
TagIt[] tagIts = destroyedObj.GetComponentsInChildren<TagIt>();
if (tagIts == null) return;
for (int i = 0; i < tagIts.Length; i++)
{
for (int j = 0; j < tagIts[i].tags.Count; j++)
{
if (tagIts[i].tags[j] == Tag.ClingingDebris)
clingingDebris.Add(tagIts[i].transform);
}
}
for (int i = 0; i < clingingDebris.Count; i++)
{
//TODO: When releasing clinging debris, we need to add back the same rigidbody configuration the object had before becoming debris.
clingingDebris[i].gameObject.AddComponent<Rigidbody>();
}
}
public static void MakeDebrisCling(this GameObject destroyedObj)
{
// Check to see if any debris pieces will be clinging to nearby rigidbodies
ClingPoint[] clingPoints = destroyedObj.GetComponentsInChildren<ClingPoint>();
for (int i=0; i<clingPoints.Length; i++)
{
Rigidbody clingPointRbody = clingPoints[i].transform.parent.GetComponent<Rigidbody>();
if (clingPointRbody == null) continue;
// Check percent chance first
if (clingPoints[i].chanceToCling < 100) // 100% chance always clings
{
int randomNbr = Random.Range(1, 100);
if (randomNbr > clingPoints[i].chanceToCling) // exit if random number is outside the possible chance.
continue;
}
// Check if there's anything to cling to.
Ray ray = new Ray(clingPoints[i].transform.position - (clingPoints[i].transform.forward * 0.025f), clingPoints[i].transform.forward); // need to start the ray behind the transform a little
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo, 0.075f))
{
if (hitInfo.collider.isTrigger) continue; // ignore trigger colliders.
clingPointRbody.transform.parent = hitInfo.collider.gameObject.transform;
// If the debris is Destructible, add DestructibleParent script to the parent so debris will get OnCollisionEnter() events.
if (clingPointRbody.gameObject.GetComponent<Destructible>() && !hitInfo.collider.gameObject.GetComponent<DestructibleParent>())
hitInfo.collider.gameObject.AddComponent<DestructibleParent>();
// If the object this debris is clinging to is also destructible, set it up so it will be released when the parent object is destroyed.
Destructible destructibleObj = hitInfo.collider.gameObject.GetComponentInParent<Destructible>();
if (destructibleObj != null)
{
destructibleObj.unparentOnDestroy.Add(clingPointRbody.gameObject);
DelayedRigidbody delayedRbody = clingPointRbody.gameObject.AddComponent<DelayedRigidbody>();
delayedRbody.mass = clingPointRbody.mass;
delayedRbody.drag = clingPointRbody.drag;
delayedRbody.angularDrag = clingPointRbody.angularDrag;
}
// Remove all cling points from this clinging debris object
ClingPoint[] clingPointsToDestroy = clingPointRbody.gameObject.GetComponentsInChildren<ClingPoint>();
for (int j = 0; j < clingPointsToDestroy.Length; j++)
Object.Destroy(clingPointsToDestroy[j].gameObject);
// Remove all rigidbodies from this clinging debris object
clingPointRbody.gameObject.RemoveAllFromChildren<Rigidbody>();
}
}
}
public static void ProcessDestructibleCollision(this Destructible destructibleObj, Collision collision, Rigidbody collidingRigidbody)
{
// Ignore collisions if collidingRigidbody is null
if (collidingRigidbody == null) return;
// Check for DontDoDamage tag on the collidingRigidbody
if (collidingRigidbody.gameObject.HasTag(Tag.DontDoDamage)) return;
// Ignore collisions if this object is destroyed.
if (destructibleObj.IsDestroyed) return;
// Check that the impact is forceful enough to cause damage
if (collision.relativeVelocity.magnitude < destructibleObj.ignoreCollisionsUnder) return;
if (collision.contacts.Length == 0) return;
float impactDamage;
Rigidbody otherRbody = collision.contacts[0].otherCollider.gameObject.GetComponentInParent<Rigidbody>(true);
// If we've collided with another rigidbody, use the average mass of the two objects for impact damage.
if (otherRbody != null)
{
if (otherRbody.gameObject.HasTag(Tag.DontDoDamage)) return;
float avgMass = (otherRbody.mass + collidingRigidbody.mass) / 2;
impactDamage = Vector3.Dot(collision.contacts[0].normal, collision.relativeVelocity) * avgMass;
}
else // If we've collided with a static object (terrain, static collider, etc), use this object's attached rigidbody.
{
Rigidbody rbody = destructibleObj.GetComponent<Rigidbody>();
impactDamage = Vector3.Dot(collision.contacts[0].normal, collision.relativeVelocity) * collidingRigidbody.mass;
}
impactDamage = Mathf.Abs(impactDamage); // can't have negative damage
if (impactDamage > 1f) // impact must do at least 1 damage to bother with.
{
//Debug.Log("Impact Damage: " + impactDamage);
//Debug.DrawRay(otherRbody.transform.position, collision.relativeVelocity, Color.yellow, 10f); // yellow: where the impact force is heading
ImpactDamage impactInfo = new ImpactDamage() { ImpactObject = otherRbody, DamageAmount = impactDamage, ImpactObjectVelocityFrom = collision.relativeVelocity * -1 };
destructibleObj.ApplyDamage(impactInfo);
}
}
public static void CalculateDamageLevels(this List<DamageLevel> damageLevels, float maxHitPoints)
{
if (maxHitPoints <= 0) { return; }
if (damageLevels == null || damageLevels.Count == 0) { return; }
// Sort the list descending on Damage Percent field.
//damageLevels.Sort((x, y) => -1 * x.damagePercent.CompareTo(y.damagePercent));
int prevHealthPercent = -1;
for (int i = 0; i < damageLevels.Count; i++)
{
if (damageLevels[i] == null) continue;
if (damageLevels[i].healthPercent <= 0)
{
damageLevels[i].hasError = true;
continue;
}
if (prevHealthPercent > -1 && damageLevels[i].healthPercent >= prevHealthPercent)
{
damageLevels[i].hasError = true;
prevHealthPercent = damageLevels[i].healthPercent;
continue; // Health percents should go down with every subsequent damage level.
}
damageLevels[i].hasError = false;
if (i == 0) // highest damage level, set max hit points to maxHitPoints of destructible object.
damageLevels[i].maxHitPoints = maxHitPoints;
else // not the highest damage level, so set the previous level's minHitPoints to this level's maxHitPoints.
{
damageLevels[i].maxHitPoints = maxHitPoints * (.01f * damageLevels[i].healthPercent);
damageLevels[i - 1].minHitPoints = maxHitPoints * (.01f * damageLevels[i].healthPercent) + .1f;
}
if (i == damageLevels.Count - 1) // lowest damage level, set min hit point range to 0.
damageLevels[i].minHitPoints = 0;
prevHealthPercent = damageLevels[i].healthPercent;
}
}
public static DamageLevel GetDamageLevel(this List<DamageLevel> damageLevels, float hitPoints)
{
if (damageLevels == null || damageLevels.Count == 0) return null;
if (hitPoints <= 0)
return damageLevels[damageLevels.Count - 1];
for (int i = 0; i < damageLevels.Count; i++)
{
if (damageLevels[i].maxHitPoints >= hitPoints && damageLevels[i].minHitPoints <= hitPoints)
return damageLevels[i];
}
return null;
}
public static void ReparentChildren(this Destructible destObj, GameObject newObj)
{
if (destObj.childrenToReParentByName != null)
{
if (destObj.childrenToReParentByName.Count > 0)
{
foreach (string childName in destObj.childrenToReParentByName)
{
Transform child = destObj.transform.Find(childName);
if (child != null)
child.SetParent(newObj.transform);
}
}
}
}
/// <summary>If autoDeativateDestructibles is set to true on DestructionManager, start the Destructible component deactivated.</summary>
/// <remarks>Very useful for trees and other terrain objects, makes performance better.</remarks>
public static void SetActiveOrInactive(this Destructible destObj, DestructionManager destructionManager)
{
if (!destObj.isTerrainTree) // non-terrain tree destructibles
{
if (destructionManager.autoDeactivateDestructibles)
destObj.enabled = false;
}
else // terrain tree destructibles
{
if (destructionManager.autoDeactivateDestructibleTerrainObjects)
destObj.enabled = false;
}
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 6eb3be1ee0fb46543b91b8fada9859a8
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,104 @@
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
// ReSharper disable ForCanBeConvertedToForeach
namespace DestroyIt
{
public static class GameObjectExtensions
{
/// <summary>Removes all components of type T from the game object and its children.</summary>
public static void RemoveAllFromChildren<T>(this GameObject obj) where T : Component
{
if (obj == null) return;
foreach (T comp in obj.GetComponentsInChildren<T>())
Object.Destroy(comp);
}
public static void RemoveComponent<T>(this GameObject obj) where T : Component
{
if (obj == null) return;
T component = obj.GetComponent<T>();
if (component != null)
Object.Destroy(component);
}
public static List<T> GetComponentsInChildrenOnly<T>(this GameObject obj) where T : Component
{
return GetComponentsInChildrenOnly<T>(obj, false);
}
public static List<T> GetComponentsInChildrenOnly<T>(this GameObject obj, bool includeInactive) where T : Component
{
var components = obj.GetComponentsInChildren<T>(includeInactive).ToList();
components.Remove(obj.GetComponent<T>());
return components;
}
/// <summary>Be sure to set SolverIterationCount to around 25-30 in your Project Settings in order to get solid joints.</summary>
public static void AddStiffJoint(this GameObject go, Rigidbody connectedBody, Vector3 anchorPosition, Vector3 axis, float breakForce, float breakTorque)
{
FixedJoint joint = go.AddComponent<FixedJoint>();
joint.anchor = anchorPosition;
joint.connectedBody = connectedBody;
joint.breakForce = breakForce;
joint.breakTorque = breakTorque;
}
/// <summary>Attempts to get the center point location of a game object's combined meshes.</summary>
/// <example>If your gameobject has multiple meshes under it which together make up a car (wheels, body, etc), this function will attempt to find
/// the centerpoint of the car, taking into account all of the child meshes.</example>
/// <param name="go">The gameobject parent containing the meshes.</param>
/// <param name="meshRenderers">Pass in the collection of mesh renderers on this game object (including children) to save on performance.</param>
/// <returns>The centerpoint location of the gameobject's meshes.</returns>
public static Vector3 GetMeshCenterPoint(this GameObject go, MeshRenderer[] meshRenderers = null)
{
// first, get all the mesh renderers on the game object and children if they are not provided
if (meshRenderers == null)
meshRenderers = go.GetComponentsInChildren<MeshRenderer>();
// if there are no mesh renderers, return a zero vector (the gameobject's pivot position).
if (meshRenderers.Length == 0)
return Vector3.zero;
// if any mesh renderer on this game object is marked as Static, return a zero vector (the gameobject's pivot position) instead
// of trying to get the bounding boxes of static meshes.
if (go.IsAnyMeshPartOfStaticBatch(meshRenderers))
return Vector3.zero;
// if we made it this far, calculate the center point of the combined mesh bounds for the object and use that.
Bounds combinedBounds = new Bounds();
MeshFilter[] meshFilters = go.GetComponentsInChildren<MeshFilter>();
foreach (MeshFilter meshFilter in meshFilters)
{
Mesh sharedMesh = meshFilter.sharedMesh;
if (sharedMesh != null) // some meshFilters do not have shared meshes.
combinedBounds.Encapsulate(sharedMesh.bounds);
}
return combinedBounds.center;
}
public static bool IsAnyMeshPartOfStaticBatch(this GameObject go, MeshRenderer[] meshRenderers = null)
{
// first, get all the mesh renderers on the game object and children if they are not provided
if (meshRenderers == null)
meshRenderers = go.GetComponentsInChildren<MeshRenderer>();
// if there are no mesh renderers, return false.
if (meshRenderers.Length == 0)
return false;
// if any mesh renderer on this game object is marked as Static, return true.
for (int i = 0; i < meshRenderers.Length; i++)
{
if (meshRenderers[i].isPartOfStaticBatch)
return true;
}
return false;
}
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 505d79f55b31a5848a3507d798740d6e
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

View File

@@ -0,0 +1,32 @@
using System.Collections.Generic;
using UnityEngine;
namespace DestroyIt
{
public static class GizmoExtensions
{
/// <summary>Creates an editor-visible Gizmo for each damage effect, showing where they will play.</summary>
public static void DrawGizmos(this List<DamageEffect> damageEffects, Transform transform)
{
if (damageEffects == null) return;
foreach (DamageEffect effect in damageEffects)
{
if (effect == null) continue;
Gizmos.color = Color.cyan;
Gizmos.DrawWireCube(transform.TransformPoint(effect.Offset), new Vector3(0.1f, 0.1f, 0.1f));
Quaternion rotatedVector = transform.rotation * Quaternion.Euler(effect.Rotation);
Gizmos.DrawRay(transform.TransformPoint(effect.Offset), rotatedVector * Vector3.forward * .5f);
}
}
/// <summary>Creates an editor-visible Gizmo for each CenterPointOverride for a Fallback Particle Effect.</summary>
public static void DrawGizmos(this Vector3 centerPointOverride, Transform transform)
{
if (centerPointOverride == Vector3.zero) return;
Gizmos.color = Color.magenta;
Gizmos.DrawWireSphere(transform.TransformPoint(centerPointOverride), 0.1f);
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: a101a46a2c7abef4687612a2c307fe1e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,14 @@
using UnityEngine;
namespace DestroyIt
{
public static class MaterialExtensions
{
public static bool IsProgressiveDamageCapable(this Material mat)
{
if (mat == null || mat.shader == null) return false;
return mat.HasProperty("_DetailMask") && mat.HasProperty("_DetailAlbedoMap") && mat.HasProperty("_DetailNormalMap") && mat.GetTexture("_DetailMask") != null &&
mat.GetTexture("_DetailAlbedoMap") != null && mat.GetTexture("_DetailNormalMap") != null;
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ae764e00d679d804f83eb97fa3b46897
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

Some files were not shown because too many files have changed in this diff Show More