Search Unity

[Released] DestroyIt - Cinematic Destruction System

Discussion in 'Assets and Asset Store' started by DeadlyAccurate, Jun 14, 2014.

  1. moltke

    moltke

    Joined:
    Apr 28, 2019
    Posts:
    109
    LOL please ignore me... I'm an idiot. thanks haha
     
    DeadlyAccurate likes this.
  2. Fibonaccov

    Fibonaccov

    Joined:
    May 5, 2020
    Posts:
    58
    Loving the asset so far. I noticed some issues with importing the DestroyItReady package.

    Assets\DestroyIt\Extras (safe to delete)\DestroyIt-Ready\Scripts\Editor\DestructibleConverter.cs(28,27): error CS1061: 'List<GameObject>' does not contain a definition for 'GetComponents' and no accessible extension method 'GetComponents' accepting a first argument of type 'List<GameObject>' could be found (are you missing a using directive or an assembly reference?)

    There is no getComponents() method on a C# List.
     
  3. DeadlyAccurate

    DeadlyAccurate

    Joined:
    Apr 2, 2013
    Posts:
    186
    Yeah, we accidentally removed an extension method and we have a fix for it in the next update. If you need the update now, we can give you the fix early.
     
    Fibonaccov likes this.
  4. Fibonaccov

    Fibonaccov

    Joined:
    May 5, 2020
    Posts:
    58
    Thanks a lot for the prompt reply! no worries I can wait. I was just experimenting with some objects I created ;) Best.

    Am just going to add a foreach() on that List to iterate and add the resulting components as it was intented - for the time being.
     
    Last edited: Jun 4, 2020
  5. OdyseeGames

    OdyseeGames

    Joined:
    Jun 24, 2020
    Posts:
    25
    I am trying to create original and destroyed models in blender to bring into Unity to user with the DestroyIt. I use the cell fracture in Blender to get my destroyed version and I get the physics to work in blender (I can play it and watch it break apart like it should). But when I import the models into Unity and into the DestroyIt demo scene to test, the destroyed version does not break into the pieces that it is supposed to. I can see that it transitioned from the original version to the destroyed version, because you can see the fragmenets, but they still stay in a solid shape. I can hit them and it stays as the original shape and goes flying around the scene, without fragmenting. I imported it from Blender to Unity as a .OBJ. Am I doing something wrong?
     
  6. zangad

    zangad

    Joined:
    Nov 17, 2012
    Posts:
    357
    Hi @jgthompson90,

    Can you check to make there are rigidbodies and colliders on the individual debris pieces of the destroyed prefab? It sounds like the destroyed version has the rigidbody and collider on the parent object, which would cause the pieces to stay together as the destroyed object gets knocked around.

    Also, check out the destroyed column in the DestroyIt demo scene:
    \Assets\DestroyIt\Demos (safe to delete)\Prefabs\Destructible Objects\Destroyed\Column Marble DEST

    You'll notice that it has rigidbodies and mesh colliders on each of the debris pieces, but no collider or rigidbody on the parent game object. This is the ideal way to setup your prefabs.

    If you're still having trouble with it, please send us your .OBJ file or export the game object as a Unity Asset Package file and we'll take a look at it. (modelsharkstudio@gmail.com)
     
  7. OdyseeGames

    OdyseeGames

    Joined:
    Jun 24, 2020
    Posts:
    25
    @zangad Each peice does not have its own rigid body. That is part of the problem. That is why I was wondering if I exported it out of Blender incorrectly. I assign each peice a rigid body in Blender, but in Unity, there is 1 rigid body and 1 mesh hat encompasses all of the peices.


     
  8. DeadlyAccurate

    DeadlyAccurate

    Joined:
    Apr 2, 2013
    Posts:
    186
    I wouldn't think the rigidbodies and colliders in Blender would translate to the rigidbodies and colliders in Unity or any other game engine. They're different engines.
     
  9. OdyseeGames

    OdyseeGames

    Joined:
    Jun 24, 2020
    Posts:
    25
    @zangad
    @DeadlyAccurate
    Well I realized where I went wrong. I was exporting the object from Blender into Unity as a .OBJ and that doesn't let you pick each piece. Once I exported it from Blender and into Unity as a .FBX, it worked perfectly. Ooops...

     
  10. OdyseeGames

    OdyseeGames

    Joined:
    Jun 24, 2020
    Posts:
    25
    And now I have another problem. I got it to work, then accidentally deleted the destroyed model. So I reimported it into Unity, placed it in the scene, everything look good. So I put it as the Destroyed version in the Destructible script. I destroy the normal version, and when it spawns the destroyed version, it comes in as 100 times larger. It is crazy. When I just placed the destroyed version in the scene and play it, it is normal, it destroys as normal. It is just when I put it in the Destructible script that is acts weird.
     
  11. OdyseeGames

    OdyseeGames

    Joined:
    Jun 24, 2020
    Posts:
    25
    Well I found the issue, just need to figure out how to resolve it. When I import the models from Blender into Unity, I get inconsistent unit conversions. When I look at the imported model, the convert units are 1cm(File) to 0.01m(Unity) and 1m(File) to 1m(Unity). But the conversion that works for me is 1cm(File) to 1m(Unity). I just need to figure out how to get that.
     
  12. OdyseeGames

    OdyseeGames

    Joined:
    Jun 24, 2020
    Posts:
    25
    For anyone who may have a similar issue. I was able to resolve it by exporting the normal ("prestine") model as a .OBJ and the damaged as a .FBX. And I received an email from the folks at Model Shark and they provided me with this solution: "
    The scale of your parent objects are different from each other. DestroyIt applies the Transform values of the undestroyed prefab to the destroyed prefab. The best way to fix it is to apply the transform values in Blender to set them to 1.0, 1.0, 1.0.

    If you need to adjust the scales in Unity, put them under an empty game object that has its transform scales set to 1.0. Adjusting the scale values of physics objects in Unity affects the way the physics works, though, so it's always best to make the model's size correct in your modeling tool and not in Unity."

    So there are a couple of ways to fix it. Thanks!
     
  13. Frozzoo

    Frozzoo

    Joined:
    Feb 27, 2014
    Posts:
    1
    I'm having the same issue, It works only with the Third Person Shooter, and when I'm running into the object, it breaks perfectly, but when I try to melee or use any melee weapon, the object doesn't take damage. Any idea?
     
  14. zangad

    zangad

    Joined:
    Nov 17, 2012
    Posts:
    357
    Hi @Frozzoo,

    Thanks for letting us know you're having an issue. It looks like Invector's melee system has changed since that video and instructions were created. I'm working on updating the instructions for integrating DestroyIt with Invector's Third Person Controller Shooter asset (which includes the "Melee" asset). I'll post updated instructions here as soon as I get it working.
     
    Last edited: Jul 7, 2020
    Frozzoo likes this.
  15. zangad

    zangad

    Joined:
    Nov 17, 2012
    Posts:
    357
    @Frozzoo,

    Below are updated instructions for integrating DestroyIt with Invector's Third Person Controller Shooter (and Melee) Combat Tempates. We updated the scripts to work with both melee and shooting. Please give it a try and let us know if you have any issues.

    Steps to Integrate DestroyIt with Invector's Third Person Controller Shooter:
    1
    ) Import DestroyIt into your Invector Third Person Controller Shooter project.
    2) Import the DestroyIt Scripts for Invector Third Person Controller 1v5 package.
    3) From the top menu in Unity, choose Window => DestroyIt => Setup Minimal.
    4) Add the Destructible script to the objects you want to make destructible.
    5) Add the vDestructible script to the same objects, at the same level as the Destructible script.
    6) (OPTIONAL) If you want to use a hit effect, add the DestroyIt HitEffects script to your object, at the same level as the Destructible script. In the "When hit by" field, choose "Everything" and in the "Use particle" field, choose the particle effect prefab you want to use for the hit effect.
    7) Run the scene. You should be able to melee the destructible object and destroy it. You should also be able to shoot the gun and destroy the object.

    Video:
     
    Last edited: Feb 13, 2021
    teamkamakiri and Frozzoo like this.
  16. OmnifariousStudios

    OmnifariousStudios

    Joined:
    Mar 12, 2018
    Posts:
    48
    First off, I love your asset. It's amazing.

    I'm working on a VR action game, and so far throwing my ragdoll enemies into the destructible walls and things is going great! But after a while, performance suffers a little with so many rigidbodies.

    So what is the best way to utilize the ActivateDestructibles.cs for performance if I want the player, the thrown ragdoll enemies, and any other items to be able to destroy the other items? I was thinking placing the script and a large trigger collider on the player and each enemy, as well as larger trigger colliders on each object so that if the thrown enemies are moving at high speed, they'll still activate the Destructible script in time. Is this the best way?

    Also, any other tips for performance?

    Thanks again for an amazing app btw!
     
  17. DromoDesigner

    DromoDesigner

    Joined:
    Mar 27, 2016
    Posts:
    73
    Hello,

    I've just bought this asset, and I am very impressed. Excellent range of destruction options, and all very clearly and logically presented.

    I do have one issue (which could be due to the settings on my computer) - whenever I add a prefab from the demo folder and press play, for the first second the game object looks pink before it gets the right colours. This also happens on the main demo scene - when I first press fire on any of the weapons a big pink square appears instead of the particle effects, but a second later the correct effects appear. I'm guessing this must be something to do with the shader, but am not sure how to fix it. This is on a desktop computer, but the same thing happens on my laptop.

    Also, when I try the quick start guide, only some of the materials work on the cube (such as the brickwork ProDamage one). However, others (such as the Brass-ProDamage) only appear as completely black (I have attached a screen shot).

    I am using the standard Unity 3D system (not HDRP or URP), on version 2019.3.15f1. Does anyone have any ideas on how I can fix this issue?

    Appreciate any help you can give!
     

    Attached Files:

    • pic1.png
      pic1.png
      File size:
      303.5 KB
      Views:
      345
  18. zangad

    zangad

    Joined:
    Nov 17, 2012
    Posts:
    357
    Hi @CoryRobertson,

    Thank you for the kind words, it means a lot to us!

    The first step in improving performance is to find out what is causing the performance degradation. The easiest thing to start with is the Stats tab on the Game window:



    Keep the stats panel open while playing your game in the editor, and pay attention to the numbers when the performance is good, and also when it's poor. You might even want to capture screenshots to compare the good/poor performance stats.

    1) If you see SetPass calls going way up while performance is poor, then you might be using too many materials that aren't batched. To fix, make sure any code that manipulates materials is using sharedMaterial when possible, to avoid creating new materials (DestroyIt is already optimized this way). Another way to fix too many setpass calls is to altas your material textures, so each material is only using a small part of a very large (2K, 4K, etc) texture.
    2) If your visible skinned meshes are high when performance is bad, then you may have too many skinned meshes in the scene and need to clean them up once they are no longer relevant to the gameplay (that's why most games remove dead characters quickly). You can fix this by putting a script like DestroyAfter.cs on a ragdoll body once it is no longer relevant to gameplay so it will be destroyed and removed from the scene.
    3) If the video memory ("19.6 MB" above) or polygons ("Tris" above) spikes when performance is bad, you may need to look at removing geometry from the scene by cleaning up visible debris over time. To fix this and other performance issues related to how many rigidbodies/debris pieces/particles are in the scene, DestroyIt has several tools to help. Take a look at the game object that has the DestructionManager and ParticleManager attached to it:



    There are several things you can tweak here. In the editor, you can mouse over each option to get a tooltip for what they do, but here are a couple of quick wins to try:
    1) If your walls break into persistent debris, try setting the Max Persistent Debris down to 200 or 100 and see if it helps. If it does, you'll need to balance how much debris remains in the scene to help the look of your game vs how well it performs.
    2) Turn on Remove Visible Debris if you don't mind that debris could be removed while it is visible to the player (ie, it will disappear in front of the player). Triple-A games do this all the time, especially for unimportant game objects like rubble/debris.
    3) You can also lower the Update Frequency to 0.1 or 0.25 increase how often it checks for debris to remove. This is helpful if your game is fast-paced and a lot of debris can pile up in a very short amount of time.
    4) If performance gets bad when there is a lot of destruction happening at once, you may be running into too many particle effects going on at the same time. In this case, adjust the Max Destroyed Particles or Max Per Destructible down by half in order to reduce the amount of particle effects that are allowed to play at the same time or on a single Destructible object.

    Beyond those tips, if you're still having performance issues, I would run the Unity Profiler (Window => Analysis => Profiler) and see what it reports when you test your scene with a lot of ragdolls and destruction. Analyzing the Profiler's data is too big to cover here, but just quickly:
    1) If you're spending too much time (ms) in Physics, you might have too many active rigidbodies in your scene. If they are debris objects, try removing them by tweaking the settings in the DestructionManager above. You can also make them sleep faster by increasing the Sleep Threshold in your project's Physics settings (Edit => Project Settings => Physics => Sleep Threshold). While you're there, also consider turning down Default Solver Iterations to somewhere around 6 to 12. 25 looks great, but is tough on your CPU/graphics card. Another thing that can cause you to spend too much time in Physics is having too many mesh colliders. For your debris pieces, try to convert your mesh colliders over to box colliders. This will help Physics performance dramatically.
    2) If you're spending most of your time (ms) on Rendering, then that's good - you're not running into performance issues related to destruction/physics. You probably just need to reduce the geometry of your destroyed prefabs, or take a look at reducing the geometry/materials on your ragdoll characters. Could be that once there are several of those in the scene, your CPU/graphics card is struggling to render it all.

    Hope that helps! :)
     
  19. zangad

    zangad

    Joined:
    Nov 17, 2012
    Posts:
    357
    Oh, and yes, if you want to keep the Destructible.cs scripts deactivated for performance and activate them with a large trigger collider on your ragdolls/player, that's the way I would do it. But you still need to know why you're getting poor performance as time goes on. I wouldn't think the active Destructible scripts would be causing that, unless the Destructible objects are being created at runtime.

    Normally, you'd only need to keep the scripts deactivated if you had thousands of them when the game starts, as is the case with a forest of destructible trees. But yeah, using the ActivateDestructibles script is another option for helping performance, especially if in the Unity Profiler you see that you're spending too much time in FixedUpdate in the Destructible.cs script.
     
  20. OmnifariousStudios

    OmnifariousStudios

    Joined:
    Mar 12, 2018
    Posts:
    48
    Wow...Thanks for the detailed reply!
    I'll look into all of these next.

    Great point!
    I had asked about that script specifically because I plan on doing large scale destructible environments (including all of the buildings in the scene) so we're talking tons of scripts total, and I wanted to see how best to use the included script and what the most efficient way of using it was. I'll post more after some tests!
     
  21. zangad

    zangad

    Joined:
    Nov 17, 2012
    Posts:
    357
    Hi @DromoDesigner,

    We're glad you're enjoying DestroyIt!

    Yes, we get the pink flash you're seeing as well. For us, it's a blue flash - it seems like the blue color started with Unity 2018, but it behaves the same way as you're describing. We see this issue all the time, in almost every asset we run in the editor. The good news is, it's only an issue in the editor, it won't affect your actual game. If you choose File => Build and Run to create a build of your scene, you shouldn't see this issue.

    I think the reason it happens is because of a (fairly new) Unity Editor feature called Async Shader Compilation:
    https://forum.unity.com/threads/2019-1-0a11-editor-weird-look-while-building-a-project.594892/

    It's actually a performance improvement feature that especially helps with large projects that have lots of shaders/materials. It keeps the Editor from lagging by displaying a dummy shader while loading the real shader in the background. If you don't like it, you can disable it in your Project Editor preferences:

    1) In your Project, go to Edit > Project Settings.. > Editor.
    2) At the bottom of the Editor settings, under Shader Compilation, uncheck the Asynchronous Shader Compilation checkbox.
    https://docs.unity3d.com/Manual/AsynchronousShaderCompilation.html

    I disabled it to test it out, and I no longer get the blue flashes, but it does pause every time it has to render one of those materials for the first time. So you can choose which one you like best for the Editor (flashes or pauses).

    Regarding the black material on the QuickStart cube - this is probably because the Brass material is highly reflective (Metallic) and there is no Reflection Probe in the scene. To fix this:
    1) Add a Reflection Probe to your scene (GameObject => Light => Reflection Probe) and position it so the cube is inside the reflection probe's box area.
    2) OPTIONAL: You may want to drop an extra Point Light in the scene, to make the light bounce off the metallic surface more (GameObject => Light => Point Light). Position the light close to the cube. Change the color if you like.
    3) Re-generate the lighting in the scene (Window => Rendering => Lighting Settings => Generate Lighting). This will create the reflection maps so the metallic material will look correct in the scene.

    Results:


    Please let us know if you are still having issues.
     
  22. DromoDesigner

    DromoDesigner

    Joined:
    Mar 27, 2016
    Posts:
    73
    Hello Zangad,

    Thank you very much for your quick and detailed reply!

    Very interesting about the asynchronous shader compilation - thank you for explaining that.

    The material on the Quick Start cube now works after following your suggestions.

    Appreciate all the advice, and the time you took to answer my questions - I'm a happy customer :)
     
  23. DeadlyAccurate

    DeadlyAccurate

    Joined:
    Apr 2, 2013
    Posts:
    186
    New version 1.12
    Now with Playmaker support!

    v1.12 (Jul 2020)

    Major Changes

    • Added PlayMaker support for Destructible Actions (Damage, Repair, Destroy) and Events (OnDamaged, OnRepaired, OnDestroyed) and illustrated it with a new PlayMaker demo scene (under Extras).

    Bug Fixes

    • Changed RepairDamage(int) to RepairDamage(float) on the Destructible script in order to support both float damage and repairing.
    • Destructible scripts would process collisions and take damage even when disabled. Now you can disable Destructible scripts and they will not process collisions, as expected. (Note: Destructible terrain trees still process collisions and take damage when the Destructible scripts are disabled, as intended).
    • Added a safety check in GetMeshCenterPoint() method to fix errors when a MeshFilter does not have a shared mesh.
    • Added safety checks to all code that un-registers an event when OnDisable() fires, to prevent the possibility of null reference exceptions.
    • Added a safety check to the ExplodeAfter.cs script to handle if there is no explosion prefab provided.
    • Fixed: Debris from ChipAwayDebris objects that were reparented to moveable objects would move along the ground with the object.
    • Fixed: Mesh center point calculation for static meshes changed from gameObject.isStatic property to meshRenderer.isPartOfStaticBatch property.
    • Fixed: Debris from destroyed objects which were added to the Object Pool manually (or not pooled at all) were not being initialized/configured properly, and velocity was not being tranferred to the debris after spawn.

    Minor Changes, Cleanups, and Enhancements

    • Updated DestroyIt to Unity 2019.4.5f1 (LTS).
    • Added the WhenDamagedDamageParents script, so you can have Destructible objects damage their parents when they are damaged.
    • Added public Destroy() method that can be called on a Destructible object to destroy it immediately.
    • Cleaned up QuickStart demo scene, removing unneeded terrain and textures.
    • Created a PlayMaker action that applies damage to a Destructible object (DamageDestructibleObject)
    • Created a PlayMaker action that destroys a Destructible object (DestroyDestructibleObject)
    • Created a PlayMaker action that repairs a Destructible object (RepairDestructibleObject)
    • Added a script to send the Damaged event from a DestroyIt Destructible to PlayMaker.
    • Added a script to send the Repaired event from a DestroyIt Destructible to PlayMaker.
    • Added a script to send the Destroyed event from a DestroyIt Destructible to PlayMaker.
    • Added a new demo scene that illustrates how to use Playmaker actions and how to listen to DestroyIt Destructible events (under Extras)
    • Updated DestroyIt User Guide, adding a section on how to use the new PlayMaker Actions.
    • Extracted the DestroyIt-Ready user guide from the nested asset package and placed it at the root of the Extras folder, so you can read it without needing to unpack anything.
    • Renamed ObjectPool container to "DestroyIt_ObjectPool" instead of "_ObjectPool" to avoid conflicts with other object pooling systems.
    • ObjectPool now checks for an existing object named "DestroyIt_ObjectPool" and uses it instead of always creating a new container object regardless.
    • Mesh center point is now only calculated for a destructible object if it uses a fallback particle effect.
    • Added a Debug.Log for when you have 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."
    • On the Destructible script, if you use a Material Override for a particle effect, the system now applies progressive visual damage on the override material if it supports it.
    • Scenario #27 (Static Meshes) in the Main Demo Scene is now split into three separate variations of the scenario, for clarity and testing.
    • Angular Velocity is now also tranferred to debris from the Destructible object that spawned it. (Before, it was only Velocity that was transferred.)
     
    jangomoose likes this.
  24. Budgieboy

    Budgieboy

    Joined:
    Sep 6, 2012
    Posts:
    40
    Hi, I see the asset works with Photon but is it possible to get it working over UNET? All I've managed to achieve is having the game object gets destroyed over networking however the physics itself doesn't work.
     
  25. zangad

    zangad

    Joined:
    Nov 17, 2012
    Posts:
    357
    Hi @Budgieboy,

    We don't have experience using UNET, but if you send us your project, we'll take a look at it and see if anything stands out.

    To help us troubleshoot your project efficiently, please do the following:
    1) Remove any assets in your project that are not required to reproduce the issue.
    2) Export the project to a *.unitypackage file.
    3) Ensure that you can import the unitypackage file into a clean project and it will build and run without errors.
    4) Upload the unitypackage to a cloud service (Dropbox/OneDrive/GoogleDrive) and email us the link (modelsharkstudio@gmail.com).
    5) In your email, let us know what version of Unity to use, as well as any special testing instructions (such as how to test the multiplayer aspects that aren't working correctly).
     
  26. moltke

    moltke

    Joined:
    Apr 28, 2019
    Posts:
    109
    Hi @zangad , so I'm using the destructible script on trees, but im using the trees as prefabs and not through the unity terrain system.

    I have the initial tree call in the destroyed tree prefab when its destroyed which i show in this video, but then i have the parent left over, and i was wondering if it would be possible to attach a script to this parent in order to pull in the original tree prefab that was there prior to it being destroyed after a period of time that can be attached to the parent that is left over after the destroyed tree disappears;

    In the end im left with the empty parent of the destroyed prefab, i was wondering if you knew of a way to replace the destroyed parent with the initial tree after so much time has passed

    here's the video explaining my issue
     
    Last edited: Aug 9, 2020
    zangad likes this.
  27. P3ndragonLLC

    P3ndragonLLC

    Joined:
    Sep 19, 2019
    Posts:
    99
    Hello, Is there an updated guide for integration with opsive since the page 9 version? I'm getting an error that EventHandler doesnt exist.

    Thanks!
     
  28. zangad

    zangad

    Joined:
    Nov 17, 2012
    Posts:
    357
    Hi @moltke,

    Thanks for the video explaining what you're trying to accomplish. I wrote a script that (I think) will do what you want. You drop this script on your destroyed prefab, at the parent game object level. For the ResetToPrefab field, set it to your original Destructible object.

    This script will reset a Destructible object back to a prefab of your choosing, after it waits for a configurable amount of time. With this script, you can reset a destroyed (non-terrain) tree back to a pristine tree, a sapling (for survival-type games), etc. It also handles position, rotation, scale, re-parenting, and object pooling of the newly-spawned reset object (as long as you set Auto-Pool to true on the Destructible script, which is the default).

    ResetDestructible.cs
    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. namespace DestroyIt
    4. {
    5.     /// <summary>
    6.     /// Place this script on your destroyed prefab, at the highest parent level.
    7.     /// When your destroyed prefab spawns in, it will wait for a while and then reset itself to whatever game object you have assigned to resetToPrefab.
    8.     /// </summary>
    9.     public class ResetDestructible : MonoBehaviour
    10.     {
    11.         [Tooltip("The game object prefab you want to reset this destructible object to after it has been destroyed. (Usually a Pristine version of this destroyed object.)")]
    12.         public GameObject resetToPrefab;
    13.  
    14.         [Tooltip("The minimum amount of time to wait (in seconds) before resetting the destructible object. (3600 seconds = 1 hour)")]
    15.         public float minWaitSeconds = 30.0f;
    16.  
    17.         [Tooltip("The maximum amount of time to wait (in seconds) before resetting the destructible object. (3600 seconds = 1 hour)")]
    18.         public float maxWaitSeconds = 45.0f;
    19.  
    20.         private float _timeLeft;
    21.         private bool _isInitialized;
    22.  
    23.         void Start()
    24.         {
    25.             if (resetToPrefab == null)
    26.             {
    27.                 Debug.LogError("ResetDestructible Script: You need to assign a prefab to the [resetToPrefab] field.");
    28.                 Destroy(this);
    29.                 return;
    30.             }
    31.  
    32.             // Randomly determine when to reset the destroyed object, based on the min/max wait seconds.
    33.             _timeLeft = maxWaitSeconds <= minWaitSeconds ? 0f : Random.Range(minWaitSeconds, maxWaitSeconds);
    34.  
    35.             Debug.Log($"[{gameObject.name}] will be reset in approximately {Mathf.RoundToInt(_timeLeft)} seconds.");
    36.  
    37.             _isInitialized = true;
    38.         }
    39.  
    40.         void Update()
    41.         {
    42.             if (!_isInitialized) return;
    43.  
    44.             _timeLeft -= Time.deltaTime;
    45.             if (_timeLeft <= 0)
    46.             {
    47.                 // Spawn the resetToPrefab object after the required wait time.
    48.                 GameObject go = Instantiate(resetToPrefab, transform.position, transform.rotation, transform.parent);
    49.                 go.transform.localScale = transform.localScale; // in case the destroyed object was scaled in the scene
    50.                 Debug.Log($"[{gameObject.name}] has been reset to [{resetToPrefab.name}].");
    51.  
    52.                 Destroy(gameObject); // remove this gameObject to cleanup the scene
    53.             }
    54.         }
    55.     }
    56. }
    I also created a video of the process:

    Please try it out and let us know if it provides the effect you're looking for.
     
  29. zangad

    zangad

    Joined:
    Nov 17, 2012
    Posts:
    357
    Last edited: Aug 11, 2020
  30. P3ndragonLLC

    P3ndragonLLC

    Joined:
    Sep 19, 2019
    Posts:
    99
    Thanks! It compiles, I'll try it out and let you know if I have any issues.
     
  31. Stefan86

    Stefan86

    Joined:
    Aug 31, 2017
    Posts:
    62
    Hey @zangad ..
    How can I save the destroyed trees so that they are no longer in the game when restarted?
     
  32. moltke

    moltke

    Joined:
    Apr 28, 2019
    Posts:
    109
    WOWOWOW!! it worked like a charm this is amazing! I can use it with rocks and other resources too! this it outstanding! Thank you so much for taking the time to write this!
     
    zangad likes this.
  33. P3ndragonLLC

    P3ndragonLLC

    Joined:
    Sep 19, 2019
    Posts:
    99
    That opsive integration works great, really satisfying experience :)

    Would you have an idea of how to do a similar kind of integration with malber's animal controller (https://assetstore.unity.com/packages/tools/animation/animal-controller-148877) to use with their dragons? I specifically want to cause damage on breath weapons, do I do something like this:
    EventHandler.RegisterEvent<float, Vector3, Vector3, GameObject, object, Collider>(gameObject, "OnObjectImpact", OnImpact);

    But the event I want to register is from the Malber's scripts?
     
    zangad likes this.
  34. zangad

    zangad

    Joined:
    Nov 17, 2012
    Posts:
    357
    Hi @Stefan86,

    Thanks for your question. I took a look at it, and here's what I came up with that seems to work. Note that the destroyed trees are saved to PlayerPrefs data in this example (you would probably want to serialize the data to a JSON file or similar in a real game), but hopefully it will get you pointed in the right direction! :)

    1) Create a new script called PlayerPrefsX.cs in your project somewhere (preferably where your DestroyIt scripts are located). Copy the code from the PlayerPrefsX wiki page (scroll down towards the bottom to get the C# version) and paste it into your PlayerPrefsX.cs file. This class will allow us to save a list of destroyed tree positions into the PlayerPrefs data storage for easy retrieval later.

    2) Copy this section of code to your DestructionManager.cs script. Insert it into the InstantiateDebris() method, immediately after the line that reads "newObj.gameObject.LockHueVariation();". This code saves each destroyed tree to PlayerPrefs, so the destroyed trees can be removed from the terrainData later, either when the scene is loaded, or when the application quits.
    Code (CSharp):
    1. // Save the tree position to a serializable object so we can recall it later.
    2. // For this example, we will save this data to the PlayerPrefs object.
    3. // In a real game, we'd want to save this information to a JSON file or similar data store.
    4. // NOTE: In order to use the PlayerPrefsX script below, you will need to copy it from http://wiki.unity3d.com/index.php/ArrayPrefs2 and drop it into your project.
    5. Vector3 destroyedTreeLoc = oldObj.transform.position;
    6. List<Vector3> destroyedTreeLocs = PlayerPrefsX.GetVector3Array("DestroyedTreeLocations").ToList(); // First, get the list of already-destroyed trees.
    7. bool alreadyExistsInList = destroyedTreeLocs.Any(x => x == destroyedTreeLoc);
    8. if (!alreadyExistsInList)
    9. {
    10.     destroyedTreeLocs.Add(destroyedTreeLoc); // Add this tree to the list of destroyed trees.
    11.     PlayerPrefsX.SetVector3Array("DestroyedTreeLocations", destroyedTreeLocs.ToArray()); // And save the list back to PlayerPrefs.
    12.     Debug.Log($"Tree at position {destroyedTreeLoc} was destroyed and saved to the list of destroyed trees for later.");
    13. }
    3) Copy this section of code to your TreeManager.cs script. Insert it at the very end of the RestoreTrees() method. This section of code loads the previously saved destroyedTrees data from PlayerPrefs and removes those trees from the terrainData. The RestoreTrees() method is fired OnApplicationQuit(), so when you destroy a tree and then exit play mode, it will remove the destroyed trees from the terrain data at that time and they will be permanently gone, so use caution if you're testing this on a terrain you haven't backed up!
    Code (CSharp):
    1. // Check each tree to see if it is in the list of ones already destroyed.
    2. // For this example, we will load this data from the PlayerPrefs object.
    3. // In a real game, we'd want to load this information from a JSON file or similar data store.
    4. // NOTE: In order to use the PlayerPrefsX script below, you will need to copy it from http://wiki.unity3d.com/index.php/ArrayPrefs2 and drop it into your project.
    5. List<Vector3> destroyedTreeLocs = PlayerPrefsX.GetVector3Array("DestroyedTreeLocations").ToList();
    6. List<TreeInstance> treeInstances = terrain.terrainData.treeInstances.ToList();
    7. List<TreeInstance> undestroyedTreeInstances = new List<TreeInstance>(treeInstances);
    8. foreach (Vector3 destroyedTreeLoc in destroyedTreeLocs)
    9. {
    10.     TerrainTree closestTree = terrain.ClosestTreeToPoint(destroyedTreeLoc);
    11.  
    12.     if (destroyedTreeLoc == closestTree.Position)
    13.     {
    14.         Debug.Log($"Tree at position {closestTree.Position} was destroyed. Removing from terrain...");
    15.         //WARNING: Removing a tree instance from your terrain (even during the game) will PERMANENTLY remove it from the TerrainData!
    16.         undestroyedTreeInstances.RemoveAll(x => x.position == destroyedTreeLoc);
    17.         undestroyedTreeInstances.Remove(closestTree.TreeInstance);
    18.     }
    19. }
    20.  
    21. // Check if we have any trees to remove from the terrain.
    22. if (undestroyedTreeInstances.Count != treeInstances.Count)
    23. {
    24.     terrain.terrainData.treeInstances = undestroyedTreeInstances.ToArray();
    25.  
    26.     // Refresh the terrain to remove the collider
    27.     float[,] heights = terrain.terrainData.GetHeights(0, 0, 0, 0);
    28.     terrain.terrainData.SetHeights(0, 0, heights);
    29. }
    30.  
    31. // Clear our list of destroyed trees
    32. PlayerPrefsX.SetVector3Array("DestroyedTreeLocations", new Vector3[0]);
    Oh - and if you're having trouble copying/pasting the code in the right spots, just drop us an email at modelsharkstudio@gmail.com and we'll send you the full, modified scripts.
     
    Last edited: Aug 13, 2020
    Stefan86 likes this.
  35. zangad

    zangad

    Joined:
    Nov 17, 2012
    Posts:
    357
    Thanks for letting us know it worked for you. :)

    Regarding MalberS Animal Controller, I'm not sure how to do that off-hand (from the EventHandler signature), but I downloaded the asset and will take a look at how to do an integration with DestroyIt for the breath weapon.
     
  36. P3ndragonLLC

    P3ndragonLLC

    Joined:
    Sep 19, 2019
    Posts:
    99
    Awesome, thanks for looking into it!
     
  37. Stefan86

    Stefan86

    Joined:
    Aug 31, 2017
    Posts:
    62
    @zangad
    wow .. it works great .. thanks a lot for your effort
     
    zangad likes this.
  38. Stefan86

    Stefan86

    Joined:
    Aug 31, 2017
    Posts:
    62
    is there also a possibility that the trees will be there again with a new game ??
     
  39. Budgieboy

    Budgieboy

    Joined:
    Sep 6, 2012
    Posts:
    40
    I managed to get it working on UNet with my project, but because I struggle with coding I only have it sort of working.

    Code (CSharp):
    1.     [Command(channel = 0)]
    2.     void CmdOnDead(int killer, int me, string killtype)
    3.     {
    4.         RpcODead(killer, me, killtype);
    5.     }
    6.  
    7.     [ClientRpc(channel = 0)]
    8.     void RpcODead(int killer, int me, string killtype)
    9.     {
    10.         OnThisThingDead();
    11.         OnKilled(killer, me, killtype);
    12.         if (DestroyOnDead)
    13.             GameObject.Destroy(this.gameObject, DestroyDelay);
    14.         Destructible[] destObjs = FindObjectsOfType<Destructible>();
    15.         Destructible destObj = gameObject.GetComponentInParent<Destructible>();
    16.         Destructible otherObj = gameObject.GetComponentInChildren<Destructible>();
    17.         var hitInfo = this.directionHit;
    18.         if (destObj != null)
    19.         {
    20.             ImpactDamage bulletImpact = new ImpactDamage() { DamageAmount = 50, AdditionalForce = 80, AdditionalForcePosition = hitInfo*5, AdditionalForceRadius = .5f };
    21.             destObj.ApplyDamage(bulletImpact);
    22.             otherObj.ApplyDamage(bulletImpact);
    23.         }
    24.     }
     
  40. zangad

    zangad

    Joined:
    Nov 17, 2012
    Posts:
    357
    Hey @P3ndragonLLC,

    I took a look at the MalberS Animal Controller, and the free pack doesn't include the dragon you mentioned (or I can't find it). However, I did see a FireBreath particle effect in the project, and it looks just like the one they use in their web demo on the Unka Dragon.

    So, while you might be able to hook into events like you mentioned, I'm thinking you won't need to, if all you want to do is have the breath weapon deal damage to DestroyIt objects. In that case, you just need to put a script on the FireBreath particle system that tells the particles to damage things they collide with.

    Here's a script that does that. Copy this script into a new file named FireBreathDamage.cs in your project, drop a DestroyIt pristine prefab into your scene (I chose the wooden tower), run Window => DestroyIt => Setup Minimal from the top menu in Unity, and add this script to the FireBreath particle prefab. Then, assuming your dragon uses that particle effect, it will damage DestroyIt destructible objects.

    FireBreathDamage.cs
    Code (CSharp):
    1. using DestroyIt;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. /// <summary>
    6. /// Put this script on a particle system to have its particles do damage to DestroyIt Destructible objects
    7. /// and apply force to rigidbodies. For this to work, the following things must be ENABLED
    8. /// in your ParticleSystem's inspector:
    9. ///
    10. /// "Collisions" CHECKED
    11. ///    "Type" set to "World"
    12. ///    "Mode" set to "3D"
    13. ///    "Send Collision Messages" CHECKED
    14. ///    "Enable Dynamic Colliders" CHECKED
    15. ///
    16. /// (Credit: https://answers.unity.com/questions/1197119/how-to-detect-when-and-where-a-particle-hits-a-sur.html)
    17. /// </summary>
    18. [RequireComponent(typeof(ParticleSystem))]
    19. public class FireBreathDamage : MonoBehaviour
    20. {
    21.     [Tooltip("For each particle that hits a Destructible object, this is how much damage it will do.")]
    22.     public float damageAmount = 0.15f;
    23.     [Tooltip("The amount of force power to apply to the rigidbodies the particles collide with.")]
    24.     public float forceAmount = 2f;
    25.     [Tooltip("The bigger the particle colliders, the more rigidbodies will be affected by the force.")]
    26.     public float particleColliderRadius = 0.15f;
    27.  
    28.     private ParticleSystem _particleSystem;
    29.  
    30.     public void Start()
    31.     {
    32.         _particleSystem = GetComponent<ParticleSystem>();
    33.     }
    34.  
    35.     public void OnParticleCollision(GameObject other)
    36.     {
    37.         var colEvents = new List<ParticleCollisionEvent>();
    38.         _particleSystem.GetCollisionEvents(other, colEvents);
    39.  
    40.         foreach (var colEvent in colEvents)
    41.         {
    42.             AddForce(colEvent.intersection);
    43.  
    44.             // Check for Destructible object and apply damage to them
    45.             var destObj = other.GetComponentInParent<Destructible>();
    46.             if (destObj != null)
    47.                 destObj.ApplyDamage(damageAmount);
    48.         }
    49.     }
    50.  
    51.     // Adds force to rigidbodies the particle effect collides with.
    52.     private void AddForce(Vector3 pos)
    53.     {
    54.         Collider[] colliders = Physics.OverlapSphere(pos, particleColliderRadius);
    55.         foreach (Collider hit in colliders)
    56.         {
    57.             if (hit && hit.GetComponent<Rigidbody>() != null)
    58.                 hit.GetComponent<Rigidbody>().AddForce(transform.forward * forceAmount, ForceMode.Force);
    59.         }
    60.     }
    61. }
    Video (no sound):

    Please try it out and see if that achieves the effect you're looking for. :)
     
    Last edited: Aug 15, 2020
    BeefyMcWhatnow likes this.
  41. P3ndragonLLC

    P3ndragonLLC

    Joined:
    Sep 19, 2019
    Posts:
    99
    Wow, thank you so much, I'll try that out and let you know how it goes!

    Update:
    That worked great! Really fun experience (and now I plan to put my coin drop prefab as the destroyed prefab to easily integrate them into the game)

    Would it be possible to have the malber's melee attacks (I don't know if the lite version has it, but the regular AC that the dragon's use has a kick) to also do damage?
     
    Last edited: Aug 17, 2020
  42. FrostedBrain

    FrostedBrain

    Joined:
    Sep 26, 2019
    Posts:
    31
    I am using MMFPSK and followed your integration guide. Seems to work well but the only prefab from the showcase I can damage are the wood tower and palm tree.
     
  43. zangad

    zangad

    Joined:
    Nov 17, 2012
    Posts:
    357
    Hi @FrostedBrain,

    Can you send us your project so we can take a look at it? There are a lot of variables at play (what version of Unity, what version of MMFPSK, what version of DestroyIt, which version of the instructions, which character controller, which weapons, which scene, etc) so it's easiest if we can just open your project and step through it.

    To help us troubleshoot your project, please do the following:
    1) Remove any assets in your project that are not required to reproduce the issue.
    2) Export the project to a .unitypackage file (select all the folders in your project, right-click and choose Export Package, include all dependencies).
    3) Ensure that you can import your new .unitypackage file into a clean project and it will build and run without errors (check the console window) and that you can still reproduce the issue.
    4) Upload the unitypackage to a cloud service (Dropbox/OneDrive/GoogleDrive) and email us the link (modelsharkstudio@gmail.com).
    5) In your email, let us know what version of Unity to use, as well as any special testing instructions (such as what scene to open that illustrates the issue).
     
  44. FrostedBrain

    FrostedBrain

    Joined:
    Sep 26, 2019
    Posts:
    31

    Hello, thanks for the reply!

    Turns out I needed the photon view components in order for me to damage the prefabs.

    What do I need to do to the tower prefab to sync it 1-1 with all players in MMFPSK?
     
  45. zangad

    zangad

    Joined:
    Nov 17, 2012
    Posts:
    357
    Hey @FrostedBrain,

    For Photon PUN, it's mostly two steps:
    • Add the [Photon.Pun.PunRPC] attribute to any method call you want to sync across the clients. For instance, when ApplyDamage() is called on a Destructible object, you'll probably want to sync that across the clients so everyone sees the damage done, so you would need to add that attribute to the ApplyDamage() method in DestroyIt.
    • Add the Photon View component to any object you wish to be synced across the clients. This will sync its position, rotation, velocity, and so on. So in the case of the tower, you would want to put the Photon View component on each destructible piece that makes up the structure (the chipboard walls, the posts, etc).
      Sidenote: You could take it a step further and put the Photon View component on the persistent debris pieces that get spawned in, but I wouldn't advise it - it would make the network traffic very chatty and most players wouldn't even notice that the debris was synced. I'd only consider it if the debris pieces were big enough to be used for cover (or falling collision damage) and you wanted that to be a big part of your game.
    Check out this post to see a step-by-step guide on how the two steps above were handled for the MFPS 2.0 Multiplayer FPS asset. The process would be very similar with any asset that uses Photon PUN for networking.
     
    Fibonaccov likes this.
  46. bferah

    bferah

    Joined:
    Jul 8, 2017
    Posts:
    13
    Hey @zangad I really like your asset and I'd like to purchase it (especially while it's discounted for students right now), however, I really want to make couple of things clear before that. I'm curious about the future HDRP and URP updates. Are they going to be free updates to the existing package on the asset store or are you planning to publish them as separate assets like some other asset publishers do?
     
  47. zangad

    zangad

    Joined:
    Nov 17, 2012
    Posts:
    357
    Hi @bferah,

    Thanks for reaching out to us. We're not currently planning to publish a separate stand-alone HDRP/URP update. The plan is for future versions of DestroyIt to use URP/HDRP instead of the Standard Shader. Customers who want to use the Unity 5 Standard Shader will need to use the 2019 LTS version of DestroyIt published on July 31, 2020.
     
  48. bferah

    bferah

    Joined:
    Jul 8, 2017
    Posts:
    13
    Thank you for your quick reply.
     
  49. Bitcore

    Bitcore

    Joined:
    Apr 14, 2018
    Posts:
    6
    Love your product, it's easy to set up and brings so much fun to any game.

    However I've been having difficulties with NWH vehicle physics implementation, driving in to trees doesn't seem to leave any impact on them at all, while the car itself takes/observes some damage(depending on the impact velocity). Tried a lot of scenarios the same scene already, every thing else seems to be working fine, except for vehicles doing damage to destroyit objects.

    Appreciate any help :)
     
  50. zangad

    zangad

    Joined:
    Nov 17, 2012
    Posts:
    357
    Hi @Bitcore, thanks for reaching out to us, and for the kind words!

    I think we can help with your integration of NWH Vehicle Physics and DestroyIt, but I have a few questions first.

    1) What version of NWH Vehicle Physics are you using? Is it the Version 2 that's currently available on the asset store, or the older deprecated NWH Vehicle Physics (Version 1)?

    2) What type of effect are you trying to achieve with the vehicle hitting a tree? Are you looking to drive over trees and have them be destroyed by the vehicle with minimum loss of vehicle momentum (arcade off-roader style), or are you looking to have the vehicle crash into trees and have its momentum stopped (realistic style), and damage would be done to both the vehicle and the tree?

    3) You mention your vehicle isn't doing damage to any of the DestroyIt objects (including trees). Is that correct? If so, I'm thinking it has something to do with how the rigidbody is handled on the vehicle. Also, is there a specific vehicle you're testing with that I should use for my testing?

    I'll reach out to the NWH Coding developer to try to get a copy of NWH Vehicle Physics so I can setup a test.
     
    Fibonaccov and Lohrion like this.