- Home /
How to add and modify multiple boxcollider2Ds through script?
Hey, I have a character controller, which I'm trying to add and modify multiple BoxCollider2Ds through script. The only thing is I'm not sure how to guarantee I grab the correct BoxCollider2D. I thought I could have a method create a local BoxCollider2D and then add it to the gameobject, but I cannot seem to figure out how to assign the BoxCollider2D. How can I assign a local variable to a gameobject?
Here's my code:
private void addBoxCollider2D(ref GameObject character, Vector2 size, Vector2 center)
{
BoxCollider2D boxCollider2D = new BoxCollider2D();
boxCollider2D.size = size;
boxCollider2D.center = center;
character.AddComponent<BoxCollider2D>();
}
Answer by robertbu · May 06, 2014 at 09:36 PM
You never use 'new' with a component. That is if the class is derived from Monobehavior and intended to be used as a component of a game object, you only use AddComponent:
private void AddBoxCollider2D(ref GameObject character, Vector2 size, Vector2 center)
{
BoxCollider2D boxCollider2D = character.AddComponent<BoxCollider2D>();
boxCollider2D.size = size;
boxCollider2D.center = center;
}
By convention, functions and classes start with upper case letters, and variables start with lower case letters.
I thought capitalization was for Public variables and functions, while lowercase was used for private variables and functions?
Nope. At least not in common usage. The compiler does not enforce these rules. But one benefit of using the rule is that you can routinely do things like:
Rect rect = new Rect(20,20,100,50);
And if you look around in unity you see this used all over:
Rigidbody vs rigidbody
Collider vs collider
Transform vs transform
GUITexture vs guiTexture;
and so on. By sticking to the convention, you always know when reading scripts if you are dealing with a class or a variable.
Yeah, I capitalize classes, and probably internal classes as well.
Your answer
Follow this Question
Related Questions
Stacking 2d blocks on each other. 0 Answers
Why is it working in JS but not C# 1 Answer
Does PolygonCollider2D.OverlapPoint() perform differently in Unity player than an Android device? 1 Answer
Unity 5.5 - How to Properly Fix 2D Box Collider Trigger? 4 Answers
Ball bounces at different heights when it shouldn't 0 Answers