x


convert GameObject to Rigidbody type

Hi,

When I find a game Object like this:

GameObject.Find("physics_body")

If I try to assign it to a variable that is typed as Rigidbody, it fails.

There is a rigidbody component applied to this model yes, and If I use the inspector it all works fine.

I get the following:

BCE0022: Cannot convert 'UnityEngine.GameObject' to 'UnityEngine.Rigidbody'.

Note that it works very well within the inspector, but how can I do the same via script? there is a conversion going on somewhere but I fail to find how to do that within a script.

How should I go about it?

thanks,

Jean

more ▼

asked Aug 18, 2010 at 12:17 PM

Jean Fabre gravatar image

Jean Fabre
3.7k 190 155 200

(comments are locked)
10|3000 characters needed characters left

2 answers: sort voted first

A GameObject and a Rigidbody are two entirely different types, so you cannot assign one to the other. As you find out, you have to get the Rigidbody component from the GameObject instead, ie:

joint.connectedBody = GameObject.Find("physics_body").rigidbody;

The reason you can do this in the inspector is that the inspector is smart, and if you drag a GameObject onto a component reference, it will automatically search the GameObject for matching components to assign. As you cannot drag a component itself, this is also needed to have an easy way to assign component references in the editor.

more ▼

answered Aug 19, 2010 at 09:52 AM

jonas echterhoff gravatar image

jonas echterhoff ♦♦
10.5k 9 37 115

(comments are locked)
10|3000 characters needed characters left

Found it after messing around desperately

you actually pass the component reference itself.

something like this:

<joint>.connectedBody = <GameObject>.GetComponent(Rigidbody);

Simple. Maybe it's in the doc somewhere, but I would say it would deserve a bit more explanation or examples on this.

Oddly enough, passing the right value solved other problems that at first seemed unrelated, I was getting errors about the connectedBody function itself, not the fact that the value passed was of the wrong type. see http://answers.unity3d.com/questions/18378/connectedbody-error-when-used-in-script

Jean

more ▼

answered Aug 18, 2010 at 12:49 PM

Jean Fabre gravatar image

Jean Fabre
3.7k 190 155 200

How could I use this in C#?

Apr 10 at 10:48 PM JuanseCoello
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x3655
x3176
x364
x192
x28

asked: Aug 18, 2010 at 12:17 PM

Seen: 4390 times

Last Updated: Apr 10 at 10:48 PM