addcomponent, question about 'AS'

Hello everybody,

in many javascript example I’ve found two ways of calling AddComponent:

g.AddComponent(Rigidbody);

or
g.AddComponent(Rigidbody) as Rigidbody;

or

g.AddComponent(“Rigidbody”) as RigidBody;

so no matters what component I’m adding, what’s the difference in using the keyword AS and not using it?

Cheers,
Giancarlo

You’re going to see “as” mostly when you’re using the result of AddComponent. Since AddComponent returns a component, you need to declare that you want what’s returned to be “Typecast” to a Rigidbody. Otherwise, if you did something like

var myRigidbody = gameObject.AddComponent(Rigidbody);
myRigidbody.mass = 10;

It will fail, because “mass” is not a field in Component. An easy way around this problem is to use the recently-added-to-Javascript generic version of AddComponent, ie. gameObject.AddComponent.<Rigidbody> ();

In this case, “as” attempts to cast the result as a RigidBody. IF the returned object is not actually a RigidBody, the result of the operation will be a null value. If you explicitly cast it: RigidBody(g.AddComponent(“RigidBody”)), and the result isn’t a RigidBody, it will throw an exception.

Specifically talking about your examples:

  1. This returns a type “Object”, so you can’t directly call any of the members on RigidBody until you cast it.

  2. This is fairly type-safe (but not at compile-time), AddComponent won’t return a non-RigidBody since you explicitly give it the type. It sill requires a run-time cast though.

  3. Technically, this isn’t so type-safe since you just pass in a string, and as far as the letter of the law in code is concerned, could possibly not return a RigidBody (more likely you would typo the “RigidBody” string, whereas in example 2, you can’t typo it; it won’t%

Oky doky! I think I’ve understand now… yeah, thanks a lot!!! :)))

Odd, I had posted also the usage of generics and credited burnumd for beating me to it, but the post cut it off at that % sign.

;_;

Glad we could help!

Curious! :frowning:

btw… where is the button that says “SOLVED” ?

There isn’t, but you can edit your opening post to indicate that.

I actually saw that part in the notification email I got about the thread, but yeah, it’s weird.