Search Unity

Bullet firing : Object reference not set to an instance of an object

Discussion in 'Scripting' started by Kardux, May 8, 2013.

  1. Kardux

    Kardux

    Joined:
    Apr 29, 2013
    Posts:
    8
    Hello everyone,

    Here's my first post on the forum (I started Unity like a week ago). For now I'm trying to finish the Stealth project (even if the tutorials don't exist : I just make it on my own).

    I now have a problem when I want the enemy to fire my player : I've been trying to solve it for hours but I can't manage to find out the problem...

    All I want to do for now is when pressing a button (here the "Attract" one) to fire a bullet from somewhere just in front of the enemy character. Later I'll need to set an explosion on contact with the player's collider and to affect it's life in consequence (but that's another thing).

    The problem I have is I get the message "Object reference not set to an instance of an object" about the line where I want to add a force to my bullet (I tried without it and it works well but the bullet just fall on the ground). My bullet is just a sphere with a rigidbody attached to it. And I am a bit disappointed because the script is almost the same as the many tutorial ones all over the net (and especially the Unity one about Instantiate use...) .

    I hope one of you will be able to help me solve this :D
    (and sorry about my English that's not my native language)

    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class BulletShooting : MonoBehaviour
    5. {
    6.     public Rigidbody bullet;
    7.    
    8.     void Update ()
    9.     {
    10.         if(Input.GetButtonDown("Switch"))
    11.         {
    12.             Rigidbody bulletInstance = Instantiate(bullet, transform.position, transform.rotation) as Rigidbody;
    13.             if(bullet!=null)
    14.                 print ("bullet exists");
    15.             if(bullet.rigidbody!=null)
    16.                 print ("rigidbody to bullet exists");
    17.             bulletInstance.AddForce (transform.forward*200);  // this line gives me the error
    18.         }
    19.     }
    20. }
    EDIT : Finally found another solution ! (I post it in case that could help someone else ;) )
    Another way to do it is to attach a script to your prefab bullet to make it appear with a force added to it :

    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class ForceOnAwake : MonoBehaviour
    5. {
    6.     public float shootingSpeed;
    7.    
    8.     void Awake()
    9.     {
    10.         rigidbody.AddForce(transform.forward*shootingSpeed);
    11.     }
    12. }
     
    Last edited: May 8, 2013