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);
}
}
}