Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Instantiated Object Null Right Away

Discussion in 'Scripting' started by VaunMakuza, Aug 12, 2015.

  1. VaunMakuza

    VaunMakuza

    Joined:
    Sep 20, 2012
    Posts:
    40
    Hey guys,

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

    Code (CSharp):
    1.  
    2.   private const int BULLET_SPEED = 150;
    3.   [SerializeField]
    4.   private GameObject _player;
    5.   [SerializeField]
    6.   private GameObject _bullet;
    7.  
    8. void Update()
    9. {
    10.      if(Input.GetKeyDown(KeyCode.Space))
    11.      {
    12.       var bullet = Instantiate(_bullet, _player.transform.localPosition, _player.transform.rotation) as Rigidbody;
    13.       bullet.AddForce(Vector3.up * BULLET_SPEED);
    14.       }
    15. }
    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,
     
  2. tonemcbride

    tonemcbride

    Joined:
    Sep 7, 2010
    Posts:
    1,083
    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);
     
  3. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    @tonemcbride
    actually that wont work in 5.# onwards, the default reference to rigidbody was removed, you'll need

    Code (csharp):
    1.  
    2. bullet.GetComponent<Rigidbody>().AddForce(...);
    3.  
    @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
     
  4. VaunMakuza

    VaunMakuza

    Joined:
    Sep 20, 2012
    Posts:
    40
    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!
     
  5. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    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.