This is similar to what’s posted before in:
Yes, so the problem is that there ought to be an attacker in that lane or program will scream error. My coding in C# is still not good… so what can I do to resolve the error? I do like Rick’s idea of halting the stream of attackers in certain lanes in the earlier levels. How can I achieve that without errors?
PS. I had my cactus shoot 2 projectiles instead of 1, hence the two firing methods. There’s possibly a neater way of having 2 projectiles, but I don’t know how to achieve that at the moment. This is just a quick way.
This is my shooter script:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Shooter : MonoBehaviour
{
[SerializeField] GameObject projectileC, gunC, projectileZ, gunZ; // can add a few variables
AttackerSpawner myLaneSpawner;
Animator animator;
GameObject projectileParent;
const string PROJECTTILE_PARENT_NAME = “Projectiles”;
private void Start()
{
SetLandSpawner();
animator = GetComponent<Animator>();
CreateProjectileParent();
}
private void CreateProjectileParent()
{
projectileParent = GameObject.Find(PROJECTTILE_PARENT_NAME);
if (!projectileParent)
{
projectileParent = new GameObject(PROJECTTILE_PARENT_NAME);
}
}
private void Update()
{
if (IsAttackerInLane())
{
// change animation state to shooting
animator.SetBool("isAttacking", true);
}
else
{
// change animation state to idle
animator.SetBool("isAttacking", false);
}
}
private void SetLandSpawner()
{
AttackerSpawner[] spawners = FindObjectsOfType<AttackerSpawner>(); // creating the array
foreach (AttackerSpawner spawner in spawners)
{
// check if spawner (of Attacker) is in the same position as our defender's current position
bool IsCloseEnough =
(Mathf.Abs(spawner.transform.position.y - transform.position.y)
<= Mathf.Epsilon);
if (IsCloseEnough)
{
myLaneSpawner = spawner;
}
}
}
private bool IsAttackerInLane()
{
// if my lane spawner child count is less than or equal to 0, then return false
// i.e. to check if there's an attacker in our defender's lane
if (myLaneSpawner.transform.childCount <= 0)
{
return false;
}
else
{
return true;
}
}
public void FireC() // Firing CactusFlower
{
GameObject newProjectile =
Instantiate(projectileC, gunC.transform.position, transform.rotation)
as GameObject;
newProjectile.transform.parent = projectileParent.transform;
}
public void FireZ() // Firing Zuchinni
{
GameObject newProjectile =
Instantiate(projectileZ, gunZ.transform.position, transform.rotation)
as GameObject;
newProjectile.transform.parent = projectileParent.transform;
}
}