Instantiated Object Null Right Away

Hey guys,

I have this snippet of code that is causing my issue:

  private const int BULLET_SPEED = 150;
  [SerializeField]
  private GameObject _player;
  [SerializeField]
  private GameObject _bullet;

void Update()
{
     if(Input.GetKeyDown(KeyCode.Space))
     {
      var bullet = Instantiate(_bullet, _player.transform.localPosition, _player.transform.rotation) as Rigidbody;
      bullet.AddForce(Vector3.up * BULLET_SPEED);
      }
}

It instantiates the object fine, but when it gets to the addforce line, it says bullet is actually NULL. Despite it being instantiated fine, anyone have any insight?

Cheers,

You can’t instantiate a GameObject as a rigid body (the rigid body is a component of the gameobject). You need to do something like this:

GameObject bullet = Instantiate(_bullet, _player.transform.localPosition, _player.transform.rotation) as GameObject;
bullet.rigidbody.AddForce(Vector3.up * BULLET_SPEED);

@tonemcbride
actually that wont work in 5.# onwards, the default reference to rigidbody was removed, you’ll need

bullet.GetComponent<Rigidbody>().AddForce(...);

@VaunMakuza

you’re mixing up the types, what you have would work if _bullet was declared at the top as a Rigidbody, if you need to keep it as a gameobject you can’t cast the instantiated gameobject into a rigidbody, you need to use GetComponent

you also probably don’t want them as private fields since you cannot set them to anything in the inspector, unless they are being inititalised to something in code elsewhere

Serialized fields allow you to set them in inspector, without having them publicly accessed elsewhere!

I managed to do basically what you said as well, with the getcomponent and it is working fine! I realized it almost exactly after I posted the question!

Thanks for the help folks!

Generally avoid as in casting unless you are going to do a null check immediately after. If you know the type, explicit casting is better. Or better still use the generic version of Instantiate.