Having trouble with instantiating bullets at multiple points via a list of transforms.
Hi, I am having trouble with Instantiating bullets at six different transforms that are stored in a List of transforms. It keeps throwing the error (NullReferenceException: Object reference not set to an instance of an object Gun.Shoot() (at Assets/Scripts/Gun.cs:21). I already threw in some Debug.Logs to see if the points I put in the list were null and they weren't so I am confused, I am also a beginner so that might be why I am stuck on this simple issue.
Here is the code:
Bullet.cs
 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 
 public class Bullet : MonoBehaviour {
     public float bulletVelocity = 100f;
 
     public List<Gun> gunSpots = new List<Gun> ();
     [HideInInspector]
     public List<Transform> muzzleSpots = new List<Transform>();
 
     void Start(){
         FindGunPositions ();
 
     }
 
     public void FindGunPositions(){
         foreach (Gun gun in gunSpots) {
             muzzleSpots.Add (gun.transform);
             //Just checking that the gun positions were not null
             //Debug.Log (gun.transform.position);
         }
     }
 
     void Update(){
         
     }
     
 
 }
 
               Gun.cs
 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 
 public class Gun : MonoBehaviour {
 
     public Bullet bulletPrefab;
     Bullet bulletInstance;
     Bullet bulletClass;
 
     void Start () {
         bulletClass = GetComponent<Bullet> ();
     }
     
     void Update () {
         Shoot ();
     }
 
     void Shoot(){
         if (Input.GetButton ("Fire1")) {
             foreach (Transform gun in bulletClass.muzzleSpots) {
                 Debug.Log (gun.transform.position);
                 bulletInstance = Instantiate (bulletPrefab, gun.position, Quaternion.identity) as Bullet;
                 bulletInstance.transform.position = bulletInstance.transform.position * Time.deltaTime * bulletClass.bulletVelocity;
             }
         }
     }
 }
 
               Thank you for the help in advance!
Answer by jgodfrey · Jul 04, 2016 at 02:38 PM
I assume your bulletClass reference is null here:
 foreach (Transform gun in bulletClass.muzzleSpots) {
                  Debug.Log (gun.transform.position);
 
               I see you try to get that reference in Start, here:
 bulletClass = GetComponent<Bullet> ();
 
               ... but I assume that's failing.
Are both of the above-posted scripts on the same game object?
Your answer
 
             Follow this Question
Related Questions
I got Some Error about how to Transform Postiton Enemy where one point can spawn 2 enemies. 1 Answer
Instantiate working in Awake but on in Update 1 Answer
Parenting Instancing and Prefab issues 0 Answers
Instantiated prefab with ui child gameobject , works differently compared to on-scene prefab 0 Answers