How to Change Rigidbody Type OnCollision/Trigger with Script?
Hi guys, I'm looking to create a script that will switch my Rigidbody 2D's body type from static to dynamic, so I can have a dummy platform in my game that will crumble when the player lands on it. This is the script I'm using, that I sort of assembled from a few different sources in the hopes that it would work! Can any advise where I'm going wrong? Cheers!
void OnTriggerEnter2D(Collider2D GameObject)
{
if (GameObject.tag == "Player")
{
if (GameObject.attachedRigidbody)
GameObject.attachedRigidbody.bodyType = RigidbodyType2D.Dynamic;
}
}
What problem are you facing? Your code seems fine (except you should rename GameObject
variable to collider
since you the object type is Collider2D
)
Hi Hellium,
Thanks for the response. I've now renamed GameObject to collider, thanks for that!
I should've also specified the results I was getting! So for context, I tried 2 character controllers for this, the standard assets platformer robot, and a character from Corgi Engine of the asset store (this is the one I plan to use, the robot was merely for testing). So using the robot I get no reaction at all from the object, using the Corgi character the player reacts on collision, jittering quickly then get s fired through the ground! The platforms for the Corgi character must be tagged as 'platforms' and I'm guessing this is what is causing the player to still collide with the platform despite it being set to Is Trigger. Touching the box with the Corgi character results in this message, in the console, I'm not sure if its relevant:
"Cannot use 'velocity' on a static body. UnityEngine.Rigidbody2D:set_velocity(Vector2)"
Since the Corgi character is getting different results to the robot I might take this directly to the asset creator, however do you think the Robot character should still cause the box to become dynamic when the player collides with its trigger?
EDIT: Can this text creator not do paragraphs?!
Answer by WorldEater · Dec 17, 2017 at 10:37 PM
you may be accessing the GameObject class instead of the gameObject instance, try naming your variable ex col and try again.
void OnTriggerEnter2D(Collider2D col)
{
if (col.tag == "Player")
{
if (col.gameObject.attachedRigidbody)
col.gameObject.attachedRigidbody.bodyType = RigidbodyType2D.Dynamic;
}
}
Your answer
Follow this Question
Related Questions
Heavy object push ligh object into wall,Heavier object push another into wall with 2D platformer 0 Answers
2D RigidBody slightly penetrates objects causing a bounce effect. 3 Answers
Network Rigidbodies act weird? 0 Answers
Rigid Body and Collision 1 Answer
Unity 5: AddForce Increases power when already being pushed towards a collider. How to make stop? 1 Answer