Hi community,
I’ve been scratching my head on this issue for almost a week now, I’ve walked the code, and ran debugging to isolate the issue but now I need some Guidance:
Background: I followed @Stuart_Marsh suggestion on revamping the spawning script HERE. I got the attackers spawining properly in the correct spawner rows, but getting a error on my shooter script.
Here are the details in full for easy reference, let me know if more information nation is needed. I didn’t include the spawner script to keep this post shorter, but it can be seen at the link above. Thanks for your guidance in advanced, I love this community.
Error:
NullReferenceException: Object reference not set to an instance of an object
Shooter.IsAttackerAheadInLane () (at Assets/Scripts/Shooter.cs:55)
Shooter.Update () (at Assets/Scripts/Shooter.cs:25)
Full shooter Script (I left my commented out ‘SetMyLaneSpawner’ to show what I tried changing
> public class Shooter : MonoBehaviour {
>
> public GameObject projectile, gun;
>
> private GameObject projectileParent;
> private Animator anim;
> private Spawner myLaneSpawners;
>
> void Start() {
> projectileParent = GameObject.Find ("Projectiles");
> anim = GameObject.FindObjectOfType<Animator>();
>
> // Creates a parent if necessary
> if (!projectileParent) {
> projectileParent = new GameObject("Projectiles");
> }
> SetMyLaneSpawner();
> }
>
> void Update() {
> if (IsAttackerAheadInLane()) {
> anim.SetBool ("isAttacking", true);
> } else {
> anim.SetBool ("isAttacking", false);
> }
> }
>
> //Look through all spawnwers and set myLaneSpawner if found
> void SetMyLaneSpawner () {
> Spawner[] spawnerArray = GameObject.FindObjectsOfType<Spawner>();
>
> foreach (Spawner spawner in spawnerArray) {
> if (spawner.transform.position.y == transform.position.y) {
> myLaneSpawners = spawner;
> return;
> }
> }
> }
> // void SetMyLaneSpawner () {
> // Spawners[] spawnerArray = GameObject.FindObjectsOfType<Spawners>();
> //
> // foreach (Spawners spawner in spawnerArray) {
> // if (spawner.transform.position.y == transform.position.y) {
> // myLaneSpawners = spawner;
> // return;
> // }
> // }
> // }
> bool IsAttackerAheadInLane() {
> // Exit if no attackers in lane
> if (myLaneSpawners.transform.childCount <= 0) {
> return false;
> }
> // If there are attackers, are they ahead of the defender?
> foreach (Transform attacker in myLaneSpawners.transform) {
> if (attacker.transform.position.x > transform.position.x && attacker.transform.position.x < 10f) {
> return true;
> }
> }
> // Attacker in lane, but behind us
> return false;
> }
>
> private void Fire () {
> //GameObject newProjectile = Instantiate (projectile);
> GameObject newProjectile = Instantiate (projectile) as GameObject;
> newProjectile.transform.parent = projectileParent.transform;
> newProjectile.transform.position = gun.transform.position;
>
> }
> }