Changing boxcollider size raises error?

  BoxCollider boxCollider = new BoxCollider(); //   BoxCollider boxCollider = new BoxCollider() { size = new Vector3(5, 5, 5)};
  boxCollider.size = new Vector3(5, 5, 5); // <<<< error here

NullReferenceException
UnityEngine.BoxCollider.set_size (Vector3 value) (at C:/buildslave/unity/build/artifacts/generated/common/modules/NewDynamics.gen.cs:2224)

This however works:

BoxCollider boxCollider = obj.AddComponent<BoxCollider>();
boxCollider.size = new Vector3(5, 5, 5);

So I MUST attach it to a gameobject on creation or weird stuff will happen?

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.

1 Like