Search Unity

Help please! Shooting in C#

Discussion in 'Scripting' started by jbury, Jul 14, 2009.

  1. jbury

    jbury

    Joined:
    Nov 7, 2008
    Posts:
    87
    Hellooooo again

    I'm trying to get my player I have moving around to actually shoot, I've had a look through the manual pages on instantiation but I'm still struggling to get it to work

    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class playerShoot : MonoBehaviour
    5. {  
    6.    
    7.     // Update is called once per frame
    8.     void Update ()
    9.     {
    10.         Object bullet = GameObject.FindWithTag("bullet");
    11.  
    12.            
    13.        
    14.             if(Input.GetButtonDown("Fire1"))
    15.             {
    16.                 GameObject muzzle = GameObject.FindWithTag("Player");
    17.                
    18.                 Object clone = Instantiate(bullet, muzzle.transform.position, muzzle.transform.rotation);
    19.                
    20.                
    21.                
    22.             }
    23.  
    24.    
    25.    
    26.        
    27.     }
    28. }
    I've tried replacing the "Object" lines with "GameObject" but I still can't get it to work, the error message I'm getting is:

    Code (csharp):
    1. NullReferenceException: The prefab you want to instantiate is null.
    Could someone please help as I'm still learning this scripting stuff and I've been trying all sorts for the last couple of hours and still can't get a bullet to come out :D

    My bullet prefab has a "bullet" tag on it, and I know the muzzle I'm using at the moment is just the player location as I wanted to just get something working before I juggle things around

    Thanks in advance for the help!
     
  2. jbury

    jbury

    Joined:
    Nov 7, 2008
    Posts:
    87
    FAIL. I just tried dragging the prefab from the project into the scene and it now works!

    Is there a way to have it automatically pull it from the project or for things like this do you need to make sure you have the object hidden in the scene somewhere that it can instantiate from?
     
  3. andor_p

    andor_p

    Joined:
    Jun 20, 2009
    Posts:
    29
  4. jbury

    jbury

    Joined:
    Nov 7, 2008
    Posts:
    87
    Thanks andor_p!