Home > front end >  How to start animation state only once per object distance check?
How to start animation state only once per object distance check?

Time:11-15

using System.Collections;
using System.Collections.Generic;
using System.Linq;
using TMPro;
using UnityEngine;
using UnityStandardAssets.Characters.ThirdPerson;

public class SpreadedFireDistanceCheck : MonoBehaviour
{
    public Transform player;
    public List<GameObject> spreadedFires = new List<GameObject> ();

    private Animator anim;
    private bool doOnce = true;

    void Start()
    {
        spreadedFires = GameObject.FindGameObjectsWithTag("Spreaded Fire").ToList();
        anim = player.GetComponent<Animator>();
    }

    private void Update()
    {
        foreach(GameObject spreadedFire in spreadedFires)
        {
            if(Vector3.Distance(player.transform.position, spreadedFire.transform.position) < 5f && doOnce)
            {
                anim.Play("Walk Backward");
                doOnce = false;
            }
            else
            {
                doOnce = true;
            }
        }
    }
}

There are 8 spreaded fires objects and I want to make that if the player is getting close to one of the spreaded fires play animation once.

The problem is that I need to make a loop so it will play the animation 8 times instead only once depending on how close the player is to one of the spreaded fires. And if two or more spreaded fires objects are in range also play the animation once.

CodePudding user response:

If what you want is if any of your spreadedFire is close enough, then play the fire animation (only) once in each frame, then you can use LinQ Any Operator:

using System.Linq;
    
    ......
    private void Update()
    {
        if (spreadedFires.Any(x => IsCloseEnough(x)))
        {
            anim.Play("Walk Backward");
        }
    }
    
    private bool IsCloseEnough(GameObject spreadedFire)
    {
        return Vector3.Distance(player.transform.position, spreadedFire.transform.position) < 5f;
    }
  • Related