Change game object to rigidbody using code
I am making a game that if a condition is true the game object will change to a ridgid body so that it can bounce off a rectangle in its path. If the condition is false it will pass through it. Can anyone help me with the code. Thank you in advance for your help.
Answer by Rickywild · Feb 07, 2017 at 05:12 PM
Put a rigidbody component onto the game object in question. Then in the script that's attached to the game object put something along the lines of,
private Rigidbody _rigidbody;
void Start()
{
_rigidbody = this.gameObject.GetComponent<Rigidbody>();
}
public void SetRigidbodyState(bool flag)
{
_rigidbody.enabled = flag;
}
Then call your SetRigidbodyState() whenever you need to bounce off or ignore it. I haven't tested the code but it'll be pretty much what you're after. Hope that helps
Answer by Lajo · Feb 08, 2017 at 06:52 AM
Thank you, I have not tested it but I did create the code. when I typed it in .enabled turned red. Not sure if that means there is a problem
Your answer
![](https://koobas.hobune.stream/wayback/20220612110535im_/https://answers.unity.com/themes/thub/images/avi.jpg)