Resetting a BoxCollider

Is doing this using code possible?
when i was looking through the Unity Script Reference for BoxColliders there didn’t seem to be a function for it. So i thought what if i delete the current boxcollider then generate a new one? wouldnt that technically serve a “reset”?

Now i was able to delete the collider but the code didnt generate a new one. i wonder is it because the Destroy operation is delayed so having the script the way i had it would mean i destroyed the box collider i generated too? Here’s what i have in the script.

if(gameObject.GetComponent<BoxCollider>().enabled)
   Destroy(gameObject.collider);

gameObject.AddComponent("BoxCollider");
gameObject.GetComponent<BoxCollider>().isTrigger = true;

what does resetting a box collider do? (what are you trying to do?)

resetting a box collider would automatically set the box collider to my gameobject. i have a gameobject for monsters thats being generated/spawned and by changing the monsterID in code i can change that monster to any other monster of my choice. so now for collision detection i want to put a boxcollider around the monster but since its the same object and all the monster sizes are different it would be a pain to write the code of the sizes individually. by resetting the boxcollider i wont have to

1 Answer

1

This trick should work. I think you need to destroy BoxCollider with:

Destroy(gameObject.GetComponent<BoxCollider>();

I've tried that first then i switched to gameObject.collider both arent working. also you're missing a )

Ok it seems that it needs another frame to actually remove the collider. I just tried using DestroyImmediate instead of Destroy and it works fine.

i was worried DestroyImmediate would cause me problems so i didnt try it. but i'll give that a try

There is also another possible way, without Immediate, just tried, works fine: void Start() { StartCoroutine(ResetCollider()); } IEnumerator ResetCollider() { this.gameObject.GetComponent().size = new Vector3(2,2,2); Destroy(this.gameObject.GetComponent("BoxCollider")); yield return 0; this.gameObject.AddComponent(); }

hm.. using a Coroutine. i thought its meant for delaying so i didnt consider it an option that'd solve this problem