Scripting noob needs help. How to make enemy stop when close to player?

Hi there!

I’m a very low level coder and all i can do is jerry rig parts of scripts to make it somewhat work for my own experiments. But i have gotten to a new problem.

I want the enemy to stop when its close to me so i can play a attack animation. Or just make it so the animation starts when it collides with my Player.

My thoughts is that i could play the animation when it collides with a collider tagged player, but im not sure how to do that…

My current code is this beautiful mess:

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

public class SimpleEnemywithMovement : MonoBehaviour
{
    Transform player;
    [SerializeField]
    float enemySpeed, distance;
    [SerializeField]
    private float socialdistancing;
    Vector3 StartPos;
    [SerializeField]
    private float Health = 100;
   
    [SerializeField]
    private Animator animator;


    // Start is called before the first frame update
    void Start()
    {
        player = GameObject.FindGameObjectWithTag("Player").transform;
        StartPos = transform.position;
        animator = GetComponentInChildren<Animator>();

    }

    // Update is called once per frame
    void Update()
    {
        animator.SetBool("Chase", false);

        distance = Vector3.Distance(transform.position, player.position);
        if(distance <= socialdistancing)
        {
            chase();
        }
      
    }

    void chase()
    {
        transform.LookAt(player);
        transform.Translate(0, 0, enemySpeed * Time.deltaTime);
        animator.SetBool("Chase", true);
   
    }

    public void TakeDamage(float damage)
    {
        Health -= damage;

        if (Health <= 0)
            Destroy(gameObject);
    }

}

Can i add something like

void OnTriggerEnter(Collider other)
Player player = other.GetComponent();
if (Player!= null)
animator.SetBool(“Attack”, true);

If anyone knows how to make a noob like me get a script where i can play a attack animation, please let me know!

I’m also new to Unity but maybe you could try something like this:

public LayerMask layerMask;
private void OnTriggerEnter(Collider other) {
    if ((layerMask.value & (1 << other.transform.gameObject.layer)) > 0) {
        Debug.Log("Hit with Layermask");
    }

    else {
                 Debug.Log("Not in Layermask");
         }
    }
}
1 Like

That worked! thanks alot! Perfect start on the weekend, now i have something new to test out! Peace to you!