- Home /
What means "as Unity.Object" on JS-Unity syntax?
Im pretty new to JS and Unity and I found the following line of code:
var boxCollider = GetComponent(BoxCollider2D) as BoxCollider2D;
I got that its taking the component BoxCollider2D from its object, but what exactly the end "as BoxCollider2D" does or means? because I removed this part of the code just to try out if it was going to work either way and it did.
Answer by rutter · Aug 21, 2014 at 07:34 PM
See Stack Overflow: Typecasting in C#. Also applies to UnityScript.
The as
operator is a "soft" typecast: if the object is of the requested type, you'll get a value; if it isn't, you'll get null
.
In the specific example you posted, the typecast is completely irrelevant, because GetComponent will be returning a BoxCollider2D already. Typecasting is only useful when you want to convert one type to a different type.
Some people use the string version of GetComponent. I don't recommend that ever.
I didnt get the last part "String version of GetComponent", what does that means? thanks for u support
GetComponent has overloads for the same named method. You can:
GetComponent("$$anonymous$$ouseLook") <-- string version of get component GetComponent() <-- Generic version, returns type of T
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Accuracy doesn't work. No enemies showing up. 1 Answer
Networking When Offline 1 Answer
How to read "mp3" or "other Audio" file from SDcard in runtime 0 Answers
Coding technique question 2 Answers