Search Unity

Changing boxcollider size raises error?

Discussion in 'Scripting' started by Napoleonite, Apr 3, 2015.

  1. Napoleonite

    Napoleonite

    Joined:
    Mar 15, 2015
    Posts:
    30
    Code (CSharp):
    1.   BoxCollider boxCollider = new BoxCollider(); //   BoxCollider boxCollider = new BoxCollider() { size = new Vector3(5, 5, 5)};
    2.   boxCollider.size = new Vector3(5, 5, 5); // <<<< error here
    3.  
    NullReferenceException
    UnityEngine.BoxCollider.set_size (Vector3 value) (at C:/buildslave/unity/build/artifacts/generated/common/modules/NewDynamics.gen.cs:2224)

    This however works:
    Code (CSharp):
    1. BoxCollider boxCollider = obj.AddComponent<BoxCollider>();
    2. boxCollider.size = new Vector3(5, 5, 5);
    So I MUST attach it to a gameobject on creation or weird stuff will happen?
     
  2. Glockenbeat

    Glockenbeat

    Joined:
    Apr 24, 2012
    Posts:
    669
    BoxCollider is a component, and these cannot/shall not be created through a constructor. Instead you need to add them as in your second example.
     
    Napoleonite likes this.