- Home /
How to safely destroy component with dependants?
I have a system where I have objects load up visually before they become usable in the game. As each object potentially has numerous scripts that can affect it or the system, I do this code:
var components = go.GetComponents<Component>();
foreach(var c in components)
{
if (c is Renderer || c is MeshFilter || c is Transform) continue;
Destroy(c);
}
This way the object will show, but all extras are gone.
The problem is that some components have dependancies. I.e. I get the exception "Can't remove NavMeshAgent because Motivator (Script) depends on it"
My temporary hack, is to have it repeat the destroy loop, so that it should have gotten it on the second pass. But I could end up with a component dependency 2 + layers deep. Is there a more elegant solution for this, that does not require building duplicate prefabs for all the objects just to have a separate visual side?
Thanks.
even though my hack sort of solves it, I still end up with exceptions in the log.
Answer by Unified2000 · May 31, 2018 at 03:23 PM
You could remove the [RequireComponent(typeof(NavMeshAgent))] attribute from the Motivator script or just disable the components instead of destroying them. Or destroy the components in the correct order.
if (GetComponent<Motivator>())
Destroy(GetComponent<Motivator>());
if (GetComponent<NashMeshAgent>())
Destroy(GetComponent<NavMeshAgent>());
In this case this still requires that either 1, I remove the requirements (which I cannot guarantee, as certain elements like RigidBody/Collider also carry this.)
Or 2, it requires that I write custom code for dealing with every new potential script. I'm hoping for a single solution that will always work. I.e. if I add another script dependency later on, I shouldn't be expected to remember to add it to this part as well.
So you can't just disable all of the components ins$$anonymous$$d of destroying them? I just tested this and Unity didn't complain if I disabled a required component.
That's a good one. Post that as another answer. :) That gives me the power to simply re-enable them after ins$$anonymous$$d of instantiating a new version.
Answer by DanVioletSagmiller · May 31, 2018 at 03:33 PM
I did find another solution. Though I'm still hoping for a clean solution that doesn't require updating as the project continues to add new classes/objects.
The components are pulled in order of how they show on the inspector, which can be dragged. I'm making sure that component dependents are above their dependencies.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
C# override a destroyed GameObject in a List 1 Answer
Unity "unequip" selected item from inventory. 1 Answer
Destroying Objects. 1 Answer