I’ve seen that their is a lot of ways to use the brackets in transform. extentions such as GetComponent(). Sometimes I hear how you should use quotation marks, no quotation marks, brackets, etc. So I just want to know once and for all:
What is the diffrence between:
transform.GetComponent(x);
transform.GetComponent("x");
transform.GetComponent(x());
and any other way of using it.
Assuming Unityscript:
transform.GetComponent(x);
This returns the component of type x.
transform.GetComponent("x");
This returns Component. Do not use this method.
transform.GetComponent(x());
This method doesn’t exist and would be a syntax error.
transform.GetComponent.< x >();
This returns the component of type x. It works exactly the same as GetComponent(x)
but is slightly slower. Don’t use this in Unityscript; the only reason you’d use this is if you were using C# and wanted shorter code that doesn’t require casting.
So really, the only thing you ever need in Unityscript is GetComponent(x)
. Everything else is worse in some way. C# is more complicated, as mentioned above, since in that case GetComponent(x)
returns Component and requires casting.
Within JavaScript, I always use this:
transform.GetComponent(ScriptName);
And it works fine, your last one 'GetComponent(x()); looks like when calling a function within that script:
transform.GetComponent(ScriptName).FunctionName();
I never use quotation marks, but I don’t think it makes a difference.
---- Additional ----
As for the Find, it works the same way only difference is that it is a little bit more heavier on Unity, as the Find will search through EVERY game object within the scene to find a match. Whereas the GetComponents, you have already identified the gameObject/transform in which you want to grab, it simply searching for a component. Example:
parent.GetComponent(Health);
Will search ONLY on the parent of the transform for a component, like a script called ‘Health’.
GameObject.Find("Health");
Will search for a game object within the scene called ‘Health’, but might not necessarily have a Health script on it
transform.GetComponent(type)
is best for performances reasons. Sometimes, passing a string would be necessary, like when referencing a C# script from JavaScript, but it should be avoided where possible. http://docs.unity3d.com/Documentation/ScriptReference/GameObject.GetComponent.html
The other way is generic functions. An example would be GetComponent< Rigidbody >();
. This is only really helpful in C#, where you would need a cast and the typeof
function otherwise: (Rigidbody)GetComponent(typeof(Rigidbody));