[HELP ME] I wanted my player AI to attack the enemy when in range

Hi, so I wanted to make my player AI to attack the enemy when in range. If the player or enemy died it will destroy it game object. I thought my script would work but it didn’t. I design it so that the player AI would stop when it in range with the enemy then it will attack (I didn’t make attack animation yet)
Note: I already make player game object have Player tag and enemy have Enemy tag.
Here is my Player Script:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using UnityEngine;

public class PlayerAIBehaviour : MonoBehaviour
{
    public float speed; //speed
    public float health; //health
    public float damage; //damage
    public float attackrange; //attackrange
    public bool moving;
    private Transform enemy;
    Rigidbody2D rb;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        enemy = GameObject.FindGameObjectWithTag("Enemy").transform;
        moving = true;
    }

    // Update is called once per frame
    void Update()
    {
        if (moving == true)
        {
            transform.position += Vector3.right * speed * Time.deltaTime;
        }
        float distanceFromEnemy = Vector2.Distance(enemy.position, transform.position);
       
        if (distanceFromEnemy < attackrange)
        {
            moving = false; 
        }
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag("Enemy"))
        {
            EnemyBehaviour EnemyScript = other.GetComponent<EnemyBehaviour>();
            EnemyScript.TakeDamage(1);
        }
    }

    public void TakeDamage(float damage)
    {
        health -= damage;
        if (health <- 0)
        {
            Destroy(this.gameObject);
        }
    }

    public void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.green;
        Gizmos.DrawWireSphere(transform.position, attackrange);
    }
}

Here my enemy script:

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

public class EnemyBehaviour : MonoBehaviour
{
    public float health; //health
    public float damage; //damage
    Rigidbody2D rb;
    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {

    }

    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.tag == "Player")
        {
            PlayerAIBehaviour PlayerScript = other.GetComponent<PlayerAIBehaviour>();
            PlayerScript.TakeDamage(1);
        }
    }

    public void TakeDamage(float damage)
    {
        health -= damage;
        if (health < -0)
        {
            Destroy(this.gameObject);
        }
    }
}

Story of my life, but not useful as far as solving the problem. Try this instead:

How to report problems productively in the Unity3D forums:

http://plbm.com/?p=220

Help us to help you.

1 Like

I also changed from < - to <= on both scripts but it still doesn’t work

The Question which still remains is,
what “exactly” doesnt work?

The TakeDamage?
The Destroy after Death?

or anything :o?

The object doesn’t get destroy after death

I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run?
  • what are the values of the variables involved? Are they initialized?

Knowing this information will help you reason about the behavior you are seeing.

1 Like

i would highly recommend Kurt-Dekker´s approach and aside of,
if you click on your GameObject in the inspector,
you can see the “health” since its declared “public”,

and aside of that,

i think i see your problem,

you ask if the health is " - 0 " :smile:

change your TakeDamage function to:

    public void TakeDamage(float damage)
    {
        health -= damage;
        if (health <= 0)
        {
            Destroy(this.gameObject);
        }
    }

ok so I used Debug.Log on

if (distanceFromEnemy < attackrange)
        {
            moving = false;

and it work!

But on the function void OnTriggerEnter2D(Collider2D other) it doesn’t work, so the code stuck on that part rn

Also does OnTriggerEnter2D is when boxcollider2D collide with another collider?

Make sure you are meeting all the requirements for this to be called. See the API for this function.

I think I need to check is trigger on box collider 2d but when I check is trigger, the AI fall through the ground. So I need to research more on that

Take a moment and work through a 2D collider / 2D trigger tutorial, perhaps the ones directly from Unity. I say this because you are combining multiple notions of what is going on. You need a collider on you, you have to have a rigidbody, the script has to be there, but the thing you are HITTING has to be a trigger for the trigger to happen.

It can help to draw a simple diagram of circles and boxes for what is what. And you CAN put more than one collider on anything you want, but I doubt you actually need that.

Ok so the player and the enemy are able to attack now but when the player collider hit the enemy collider, both game object get destroy. When the player attack the enemy, I only want the enemy to lose health, not both the player and enemy. How do I fix this?

NVM, I got it working now :smile:

1 Like