Adam Sancho
Adam Sancho

Reputation: 187

Unity, on enemy, multiple times BUG

I have a prefab for an enemy, if i put this same prefab more than 1 time in the same scene only 1 of them works, that one which works is always the last prefab i did put in the scene:

The other enemies are there but part of the scripts seems not working, and the other part yes.

Foc scriptFoc;
    GameObject focGO;
    private Animator animator;
    private Transform target;
    private Vector3 relativePoint;

    private float tempsActual = 0.0f;
    private bool foc = true;

    public float duracioNormal;
    public float duracioFoc;

    void Start () {
        target = GameObject.FindGameObjectWithTag("Player").transform;
        animator = this.GetComponent<Animator>();
        focGO = GameObject.FindGameObjectWithTag("Foc");
        scriptFoc = focGO.GetComponent<Foc>();
        scriptFoc.actiu();
    }

    void Update ()
    {
        if (drac_Actiu())
        {
            if(!foc)
            {
                tempsActual += Time.deltaTime;
                if (tempsActual >= duracioNormal)
                {
                    scriptFoc.actiu();
                    tempsActual = 0.0f;
                    foc = true;
                    animator.SetBool("Foc", true);
                }
            }
            else if(foc)
            {
                tempsActual += Time.deltaTime;
                if (tempsActual >= duracioFoc)
                {
                    scriptFoc.inactiu();
                    tempsActual = 0.0f;
                    foc = false;
                    animator.SetBool("Foc", false);
                }
            }
        }
    }

    private bool drac_Actiu()
    {
        relativePoint = transform.InverseTransformPoint(target.position); //Punt del jugador

        if (relativePoint.x < 2.0f || relativePoint.x > -2.0f)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

Do you have any ideas? Thank you!

Upvotes: 0

Views: 74

Answers (2)

Ethan The Brave
Ethan The Brave

Reputation: 287

focGO = GameObject.FindGameObjectWithTag("Foc");

Unless I'm reading this wrong, you're having each of your instances look for a game object by its tag, and so it's entirely possible that they are all finding the same one (the last one you added to the scene).

I believe you might just want to go with "this.[whatever]". Ex:

scriptFoc = this.GetComponent<Foc>();

Upvotes: 1

Sam Marion
Sam Marion

Reputation: 690

There's not really enough information to know for sure. What part of the script is not working? You said parts of it does?

Did you forget to set the values of your public variables in the inspector for some of the game objects?

Is every gameobject tagged with "Foc" if so focGO is probably the last gameobject you added since its just going to look for one then stop checking.

These are my guesses based on the information given.

Upvotes: 1

Related Questions