- Home /
Difference between capitalized component in AddComponent and Destroy
I am still not sure what the difference is between
AddComponent(Rigidbody)
and AddComponent(rigidbody)
???
It seems that if you add component a Rigidbody
(capitalized), you can reference it as rigidbody
(lowercase) automatically.
But, Destroy(rigidbody)
will generate a syntax error...
Answer by syclamoth · Jan 25, 2012 at 01:45 AM
Well now. You're talking about a few different things here.
The capitalised 'Rigidbody' is the typename, and the lowercase 'rigidbody' is the automatic lookup value in the Component class which automatically returns the first found instance of the class 'Rigidbody'. The important difference here is the usual best-practice one-
UpperCase for classes,
lowerCase for objects.
Did you actually try using AddComponent(rigidbody)? Since 'rigidbody' is not a valid type, I somehow doubt that that would work at all.
The automatic lookup for 'Rigidbody' components is something set up for you by the base classes all JS scripts derive from. It's not magical, and neither is it a pattern: for example, you could create a script 'MyComponent' and use AddComponent(MyComponent) to add one to your object, however, you would not then be able to refer to it automatically as 'myComponent' without first using the line
var myComponent : MyComponent = GetComponent(MyComponent);
Which, of course, manually defines it.
As for the last part, I really don't see what's going on.
Destroy(rigidbody);
should only return an error if there is no rigidbody already on the object, which is to say, nothing to destroy. Otherwise, it should just destroy the first Rigidbody-type component that it can find.
Answer by luizgpa · Jan 25, 2012 at 01:49 AM
Rigidbody is a type. rigidbody is a "reference" to a Rigidbody attached to the GameObject. Actually this code
var body = rigidbody;
is equivalent to this one
var body : Rigidbody = GetComponent(Rigidbody);
AddComponent requires a type as parameter, while Destroy requires a reference to an object.
I know that UnityScript syntax sometimes changes between versions, but in 3.2 both AddComponent(rigidbody) and Destroy(Rigidbody) show an error (No appropriate version of 'XXX' for the argument list '(YYY)' was found), while AddComponent(Rigidbody) and Destroy(rigidbody) are fine (syntax-wise).
Your answer
Follow this Question
Related Questions
using Contains(gameObject) to find and destroy a gameObject from a list 2 Answers
"Some objects were not cleaned up when closing the scene" 1 Answer
How can I destroy a GameObject from a Rigidbody variable? 1 Answer
Why doesn't this script work?? Please help.. 1 Answer
Clearing a LineRenderer Whiteboard, so that you can start drawing again 1 Answer