Search Unity

[SOLVED] AddComponent cannot AddComponent

Discussion in 'Scripting' started by sirio21, Jul 19, 2016.

  1. sirio21

    sirio21

    Joined:
    Mar 11, 2013
    Posts:
    114
    Hi,, sure that is a stupid question but i cannot do it!!

    I dont find how to do it...


    BoxCollider2D bcol = new BoxCollider2D();

    GameObject go = new GameObject("kk");
    go.AddComponent < (BoxCollider2D)bcol >(); // here how i can add the collider to the go?
     
  2. ChrisMC

    ChrisMC

    Joined:
    Jul 5, 2016
    Posts:
    1
    Code (CSharp):
    1. go.AddComponent<BoxCollider2D>();
     
  3. passerbycmc

    passerbycmc

    Joined:
    Feb 12, 2015
    Posts:
    1,741
    Code (CSharp):
    1. go.AddComponent<BoxCollider2D>();
     
  4. sirio21

    sirio21

    Joined:
    Mar 11, 2013
    Posts:
    114
    Code (csharp):
    1.       BoxCollider2D bcol = new BoxCollider2D();
    2.                 bcol.isTrigger = true;
    3.                 bcol.size = new Vector2(x, y);
    4.                 bcol.transform.localPosition =  new Vector3(x * width, y * height, 0 );
    5.                 GameObject go = new GameObject("x" + x.ToString() + " y" + y.ToString());
    6.                 go.AddComponent < (BoxCollider2D)bcol >();
    7.                 go.transform.parent = transform;
    8.  
    Having this how can i add " bcol " to gameobject " go" ?
     
  5. passerbycmc

    passerbycmc

    Joined:
    Feb 12, 2015
    Posts:
    1,741
    Code (CSharp):
    1. var bcol = go.AddComponent<BoxCollider2D>();
    2. bcol.isTrigger = true;
    3. ...
    just use the code i posted, you Don't have to instantiate or use "new" to create Components, just use AddComponent with the type parameter of the component you want to create.

    If you want to configure the collider, the new component is returned from AddComponent<T>, so you can configure it after adding it.
     
  6. sirio21

    sirio21

    Joined:
    Mar 11, 2013
    Posts:
    114
    Thanks !!