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!