- Home /
Programmatically add rigidbody2d
I'm having some trouble programmatically adding a Rigidbody2D
, as every time I try to I get this error:
Code:
Rigidbody2D rigid = player.AddComponent<Rigidbody2D> ();
I've even tried to destroy the BoxCollider
with this piece of code (Before adding the rigidbody):
Destroy (player.GetComponent("BoxCollider"));
But nothing seems to work....
EDIT: This is my player generation code:
GameObject player = GameObject.CreatePrimitive (PrimitiveType.Cube);
player.transform.position = new Vector3 (0, sizes.height, 0);
player.renderer.material.color = Color.red;
player.name = "Player";
player.AddComponent<Player>();
Destroy (player.GetComponent("BoxCollider"));
player.AddComponent<BoxCollider2D> ();
Rigidbody2D rigid = player.AddComponent<Rigidbody2D> ();
rigid.mass = 5;
Answer by Mobilpadde · Nov 03, 2014 at 02:11 PM
Had to use DestroyImmediate (player.GetComponent("BoxCollider"))
instead of Destroy (player.GetComponent("BoxCollider"));
as Destory
only removes the BoxCollider after the frame has ended.
Answer by Mayank Ghanshala · Nov 01, 2014 at 11:23 AM
You have set BoxCollider to player. Set BoxCollider2D instead first. You cant use 3d and 2d Physic component together
Yea, I understand why you'd think so, but I don't ever set any kind of BoxCollider
...it just sort of sets itself some how.
This is my player generation code:
GameObject player = GameObject.CreatePrimitive (PrimitiveType.Cube);
player.transform.position = new Vector3 (0, sizes.height, 0);
player.renderer.material.color = Color.red;
player.name = "Player";
player.AddComponent<Player>();
Destroy (player.GetComponent("BoxCollider"));
player.AddComponent<BoxCollider2D> ();
Rigidbody2D rigid = player.AddComponent<Rigidbody2D> ();
rigid.mass = 5;
Your answer
Follow this Question
Related Questions
BoxCollider2D error 1 Answer
Weird 2d collision behaviour 1 Answer
What's a good way at keeping a ball bounce around inside the scene? 1 Answer