Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Bullets and force - Error in Rigidbody2D

Discussion in '2D' started by D2Sloth, Jan 23, 2015.

  1. D2Sloth

    D2Sloth

    Joined:
    Jan 23, 2015
    Posts:
    5
    Having problem getting my bullets to fly :).
    Game creates bullets correctly but the force is not applied :(

    bullet.rigidbody2D.AddForce(new Vector2(0,1) * bulletSpeed);

    NullReferenceException: Object reference not set to an instance of an object
    DUDEMOVEGODDAMMIT.Update () (at Assets/Scripts/DUDEMOVEGODDAMMIT.cs:52)

    There seems to be problem with my Rigidbody2D bullet??
     
  2. Ramsdal

    Ramsdal

    Joined:
    Oct 18, 2013
    Posts:
    251
    I might be misunderstanding but from the exception it would seem that the problem is not about the force, but rather that either the "bullet" or "rigidbody2D" is null? (Assuming what you linked was line 52).

    Also is is kinematic needs to be unchecked: http://docs.unity3d.com/Manual/class-Rigidbody2D.html
     
  3. U3DA

    U3DA

    Joined:
    Jan 23, 2015
    Posts:
    3
    If you are using Unity5, you need to write the code in this form:

    bullet.GetComponent<Rigidbody2D>().AddForce(new Vector2(0 ,1) *bulletSpeed);

    Make sure you have a rigidbody2D attached to the gameObject too.
    Regards
     
  4. D2Sloth

    D2Sloth

    Joined:
    Jan 23, 2015
    Posts:
    5
    Here is the code:

    public GameObject bullets;
    void SpawnBullets () {
    Rigidbody2D bullet = Instantiate (bullets, new Vector3 (transform.position.x, transform.position.y, 0.0f), transform.rotation) as Rigidbody2D;
    bullet.rigidbody2D.AddForce(new Vector2(0,1) * 0.001f);

    The problem is probably in my C# cause I have never writen it before :p. I have tried both of the creating and adding force separately and they work...
     
  5. Senladar

    Senladar

    Joined:
    Jan 1, 2015
    Posts:
    45
    You Instantiate "bullets" but try and move "bullet"
     
  6. hippocoder

    hippocoder

    Digital Ape Moderator

    Joined:
    Apr 11, 2010
    Posts:
    29,723
    Although correct, I would ask that GetComponent go into a temporary reference variable first, which is then checked for null before proceeding. I code mostly defensively and it costs no extra performance to do so, and will probably save on tears later.
     
    theANMATOR2b likes this.