@@@ UNITY/이론
[UNITY] 오브젝트 상호작용
HTG
2023. 1. 19. 17:13
728x90
오브젝트와 상호 작용을 하는 코드를 위해서 OnTrigger 함수들을 활용했다.
OnTrigger 함수
- OnTriggerEnter
- 물체간의 충돌이 처음 일어났을 때 호출
- OnTriggerStay
- 물체간의 충돌이 일어난 후 충돌이 지속될 때 호출
- OnTriggerExit
- 물체간의 충돌이 끝나는 순간에 호출
void OnTriggerEnter(Collider other)
{
Debug.Log(other.gameObject.name);
Debug.Log(other.gameObject.tag);
}
void OnTriggerStay(Collider other)
{
Debug.Log(other.gameObject.name);
Debug.Log(other.gameObject.tag);
}
void OnTriggerExit(Collider other)
{
Debug.Log(other.gameObject.name);
Debug.Log(other.gameObject.tag);
}
이를 활용하여 collider에 istrigger 설정을 하고 충돌이 일어나면 상호작용을 할 수 있는 것으로 판단
// 상호작용할 물체
public GameObject interactionObject;
// 코드
private void OnTriggerStay(Collider other)
{
// 이미 상호작용하고 있는 것
if (interactionObject != null)
return;
// 해당 태그에 해당하는 오브젝트의 trigger와 만난다면
if (other.gameObject.tag == "Chair_O")
interactionObject = other.gameObject;
}
// 오브젝트 태그 리스트를 만들어서
private void OnTriggerStay(Collider other)
{
if (interactionObject != null)
return;
for (int i = 0; i < objList.Length; i++)
{
if (objList[i] == other.gameObject.tag)
{
interactionObject = other.gameObject;
}
}
}
// 상호작용을 안할 때
private void OnTriggerExit(Collider other)
{
if (!isLocalPlayer)
{
return;
}
//interactionObject = null;
for (int i = 0; i < objList.Length; i++)
{
if (objList[i] == other.gameObject.tag)
{
var outline = other.gameObject.GetComponent<Outline>();
outline.OutlineWidth = 0f;
interactionObject = null;
break;
}
}
}
이런 식으로 trigger를 작동하고 있으면 상호작용하도 있다고 판단!
728x90