- Home /
Destroy all scripts on object.
Is there any way I can destroy all components on an object, but still keeping the Transform and the GameObject itself?
Answer by tanoshimi · Jun 14, 2016 at 07:03 AM
GetComponents(typeof(Component));
Will give you an array of all components on the object. Iterate over the array and call Destroy () on each item.
Thank you! I will test this out in a bit.
This should work perfectly, I didn't know that you could use typeof(Component).
Answer by Dibbie · Jun 14, 2016 at 01:49 AM
You could use the Destroy and GetComponent method.
Destroy(this.gameObject.GetComponent<Script1OnThisObject>());
would then destroy "Script1OnThisObject" that is on the current game object - assuming that script actually exists, that is.
Thank you for your reply, Dibbie.
I know how to delete a certain component, or even all of a certain component. But there are over 20 different components (most inactive) that I need all destroyed if the NetworkView isn't $$anonymous$$e.
Basically all components except for the GameObject itself and the Transform.
Ah I see - you could try a for-loop then
//Untested - C#
private List<Component> componentList = this.GameObject.GetComponents(Component); //this would be a global declaration
for(int i = 0; i < componentList.Count() - 1; i++){
if(componentList[i] != typeOf(Transform)){
Destroy(componentList[i]);
}
}
You could also remove all the scripts on your prefab at design time, then if the object is supposed to be yours, re-add each one by code, or alternatively, "disable" every component that should not be running, then you can use the same idea above, except check if the component is enabled ins$$anonymous$$d of checking if the type of Transform. The above method will only keep the Transform on that object.
Thank you!
this part: if(componentList[i] != typeOf(Transform)){ plus tanoshimi's answer should work perfectly!
Answer by wuxingogo · Jun 14, 2016 at 09:39 PM
This code can Destroy all component.But the component that depends on other Component don't work.Sorry my english.
public void DestroyAllComponent1( GameObject go )
{
var components = GetComponents<Component>();
foreach( var t in components )
{
if( t is Transform )
continue;
Destroy( t );
}
}
Thank you, but I've already got an answer and it worked perfectly.
It sped my game up by a good 10-15FPS on my friends' old computers when we're playing multiplayer.
Also, what is up with the fact that this looks like both C# and JS?
It's csharp code .Then you can have a try.The grammar perhaps looks like js.