Notice
Recent Posts
Recent Comments
Link
박민혁의 개발
유니티 OnTriggerExit에 대한 오해 본문
trigger exit
using System.Collections;
using System.Collections.Generic;
using Unity.Collections;
using UnityEngine;
using UnityEngine.Rendering;
public class A0217_1 : MonoBehaviour
{
float buffAmount = 1;
float time = 0;
int maxtime = 5; //사라지는시간
List<PlayerStatHandler> target = new List<PlayerStatHandler>();
private void OnTriggerEnter2D(Collider2D collision)
{
PlayerStatHandler targetstat = collision.GetComponent<PlayerStatHandler>();
if (targetstat != null)
{
target.Add(targetstat);
Debug.Log($"현재 첫 스피드 {targetstat.Speed.total} 타겟 카운트 {target.Count}");
targetstat.AtkSpeed.added += buffAmount;
targetstat.Speed.added += buffAmount;
Debug.Log($"상승된 첫 스피드 {targetstat.Speed.total} 타겟 카운트 {target.Count}");
Debug.Log("플레이어입장");
}
}
private void OnTriggerExit2D(Collider2D collision)
{
PlayerStatHandler targetstat = collision.GetComponent<PlayerStatHandler>();
if (targetstat != null)
{
target.Remove(targetstat);
targetstat.AtkSpeed.added -= buffAmount;
targetstat.Speed.added -= buffAmount;
Debug.Log($"하락한 {targetstat.Speed.total} 타겟 카운트 {target.Count}");
Debug.Log("플레이어퇴장");
}
}
private void FixedUpdate()
{
time += Time.deltaTime;
if (time >= maxtime)
{
goodbye();
}
}
private void goodbye()
{
Debug.Log("들어옴");
if (target != null)
{
Debug.Log($"{target.Count}");
for (int i = 0; i < target.Count; ++i)
{
target[i].AtkSpeed.added -= buffAmount;
target[i].Speed.added -= buffAmount;
Debug.Log($"하락한 {target[i].Speed.total} 타겟 카운트 {target.Count}");
target.Remove(target[i]);
}
}
Destroy(gameObject);
}
}
위의 코드에서 굿바이는 이 오브젝트가 사라지기 전 리스트의 대상을 지워주는 코드이다
그 이유는 exit즉 범위 밖으로 안나간 대상이 있다면 제거 해야하기 때문인데
놀랍게도 triger안에 있는 상태로 그 해당 오브젝트가 사라질시
자동으로 trigger exit가 발동된다!
즉 해당 코드는 오브젝트가 사라지며 exit에서 한번 goodbye에서 1번 총 2번 스탯을 깎아 주기 때문에 버프를 받을수록 약해지는 타입
'TIL' 카테고리의 다른 글
컴포넌트 체크 이렇게 하기 (1) | 2023.12.19 |
---|---|
캐릭터 주위를 원 운동 하는 코드 (0) | 2023.12.19 |
유니티 트리거 엔터로 반사각 (1) | 2023.11.27 |
유니티 생성한 프리팹의 겟컴포넌트하지 않고 해당 클래스 바로 접근하기 (0) | 2023.11.15 |
유니티 델리게이트 이벤트 초기화 하기 (0) | 2023.11.14 |