본문 바로가기
Programing/Unity

[Unity] 유니티 2d 오브젝트 클릭시 이름 가져오기

by TEXTBOX 2022. 1. 25.
728x90

유니티에서 2d 인 경우 화면상 클릭 시 해당 클릭된 collider의 object를 가져오는 방법이다.

void Update()
{
		//마우스 클릭시
        if (Input.GetMouseButtonDown(0))
        {
        	//마우스 클릭한 좌표값 가져오기
            Vector2 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            //해당 좌표에 있는 오브젝트 찾기
            RaycastHit2D hit = Physics2D.Raycast(pos, Vector2.zero, 0f);

            if (hit.collider != null)
            {
                GameObject click_obj = hit.transform.gameObject;
                Debug.Log(click_obj.name);

            }

        }
}
728x90

댓글