All defenders are shooting simultaneously

Edit. I was able to solve the problem by changing spawner’s transform to 0. This way I was able to use Mathf.Abs instead of Mathf.Floor. Feel kinda stupid but hey, atleast it works now :smiley:

Feel free to lock the topic.

Hi!

For some reason, all my Defenders are shooting at the same time. It seems that even if only one lane has enemies on it, every instance of the defenders will star shooting. The code is underneath this message:

Please note that i used Mathf.Floor instead of Mathf.Abs because my defenders would not line up correctly.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Shooter : MonoBehaviour
{

[SerializeField] GameObject projectile;
AttackerSpawner myLaneSpawner;
Animator animator;

private void Start()
{
    SetLaneSpawner();
    animator = GetComponent<Animator>();
}

private void Update()
{
    if (IsAttackerInLane())
    {
        animator.SetBool("IsAttacking", true);
    }
    else
    {
        animator.SetBool("IsAttacking", false);
    }
}

private void SetLaneSpawner()
{
    AttackerSpawner[] spawners = FindObjectsOfType<AttackerSpawner>();

    foreach (AttackerSpawner spawner in spawners)
    {
        bool IsCloseEnough = (Mathf.Floor(spawner.transform.position.y - transform.position.y) <= Mathf.Epsilon);
        if (IsCloseEnough)
        {
            myLaneSpawner = spawner;
        }
    }
}

private bool IsAttackerInLane()
{
    if (myLaneSpawner.transform.childCount <= 0)
    {
        return false;
    }
    else
    {
        return true;
    }
}


public void Fire()
{
    Instantiate(projectile, transform.position, transform.rotation);
}

}

I took another look at this and it seems that all the defenders shoot only when there is an enemy on the lane, on which the last defender was placed. So if there are Defenders on lanes 1-3 and I place one on lane 5, the defenders will only shoot if there is an enemy on lane number 5. I have no idea what could be the problem here…

Hi Nukemin,

This sounds like a problem with a reference. First of all, add Debug.Logs to your code to figure out which spawner was assigned to which shooter. Secondly, double check if the correct Animator component got assigned to your script instance.

Here is an example:

Debug.Log(GetInstanceID() + ": Shooter Animator component: " + animator.GetInstanceID(), animator.gameObject);

The first instance id refers to the Shooter instance, the second one to the references Animator instance. If different Shooter instances have a reference to the same Animator instance, you found the problem.

Thanks for the advice!

I was able to fix the issue by playing around with the coordinates. All is working as it should now!
:slight_smile:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms