I created a spawn point and spawned several enemies.
However, I wrote a script for these enemies to stop and throw spears when they see the player’s unit. However, among these enemies, only the enemy spawned at spawn point 2 performs this action, and the remaining enemies do not throw spears or stop moving. came.
What’s the problem?
public class Demon : MonoBehaviour
{
public float speed = 0.3f; // 적의 이동 속도
public float detectionRange = 0.2f; // 플레이어 감지 범위
public GameObject spearPrefab; // 투척 무기 프리팹
public Transform firePoint; // 'spear'를 발사할 위치
public float curTime = 0f;
public float maxTime = 0.3f;
private Rigidbody2D rb;
private bool isMoving = true;
void Start()
{
rb = GetComponent<Rigidbody2D>();
curTime = 0f;
}
void Update()
{
TimeCnt();
if (isMoving)
{
// 플레이어 감지 체크
CheckForPlayer();
Move();
}
else
{
rb.velocity = Vector2.zero;
}
PlayerAttack();
}
void CheckForPlayer()
{
GameObject player = GameObject.FindGameObjectWithTag("player_unit");
if (player != null)
{
// 플레이어와의 거리 계산
float distanceToPlayer = Vector2.Distance(transform.position, player.transform.position);
// 플레이어와의 거리가 detectionRange 이하일 경우 이동을 멈추고 'spear'를 발사
if (distanceToPlayer <= detectionRange)
{
isMoving = false;
}
}
}
void PlayerAttack()
{
GameObject player = GameObject.FindGameObjectWithTag("player_unit");
float distanceToPlayer = Vector2.Distance(transform.position, player.transform.position);
if (distanceToPlayer <= detectionRange && curTime >= maxTime)
{
LaunchSpear();
curTime = 0;
}
}
void TimeCnt()
{
curTime += Time.deltaTime;
}
void Move()
{
// Rigidbody2D를 이용한 이동
rb.velocity = new Vector2(0f, -speed);
}
void LaunchSpear()
{
// 'spear' 프리팹을 'fire_point'에서 생성
GameObject spear = Instantiate(spearPrefab, firePoint.position, firePoint.rotation);
// 몇 초 후에 'spear' 오브젝트 파괴 (예: 2초 후에 파괴)
Destroy(spear, 2f);
}
}