본문 바로가기
유니티/기초

유니티 게임 오브젝트 찾기

by 노튜 2025. 2. 15.
728x90
반응형

 

1. 제네릭 타입 (T)

T는 제네릭 형식(Generic type)으로 클라이언트가 제네릭 형식의 인스턴스를 만들 때 지정하는 특정 형식에 대한 자리 표시자이다 [1].  제네릭 형식은 서로 다른 형식 인수를 사용할 수 있어 유용하다. 

 

2. 유니티 Find() 함수

유니티 Find 계열 함수는 기본적으로 대상 오브젝트를 찾기 위해 모든 오브젝트를 순회한다. 모든 오브젝트를 순회한다는 것은 유니티의 Find 계열 함수는 성능에 영향을 줄 수 있다는 의미이다. 오브젝트 생성이 적은 소규모 프로젝트에서는 성능상의 문제를 발생시키지 않을 수 있다. 하지만 유니티 프로젝트에 생성된 오브젝트가 증가하면 증가할수록 찾는 속도는 느려진다. 일반적으로 프레임(Frame)마다 호출되는 Update, LateUpdate, FixedUpdate에서는 사용을 자제하도록 하고 있다.

Find 계열 함수는 기본적으로 찾는 대상 오브젝트 중에서 유니티 프로그램이 실행되어 처음으로 활성화된 개체를 반환한다. 다시 말해 찾고자 하는 대상 오브젝트가 여러 개일 경우 Find 함수를 사용하여 찾은 대상 오브젝트가 실제 찾으려고 한 대상 오브젝트가 아닐 수 있다.

 

본 글의 작성자(Notyu)는 대안으로 다음의 방법들을 제안한다.

2.1 정적 멤버 변수 (static Member)

찾는 대상이 하나일 경우에 정적 멤버를 두는 방법이다. 프로그래밍에서 사용되는 패턴 중에 하나이다.   

using UnityEngine;

public class FindTest : MonoBehaviour
{

  // Start is called before the first frame update
  void Start()
  {
    Debug.Log(Test.Instance.testValue);
  }
  // Update is called once per frame
  void Update()
  {
    Debug.Log(Test.Instance.testValue);  
  }
}


public class Test : MonoBehaviour
{
  private static Test instance; // static Member
  public static Test Instance{get {return instance;} set {}}
  
  public float testValue = 10.0f;
  // Awake is called 
  void Awake()
  {
    instance = this;
    // DontDestroyOnLoad(this);
  {
}

 

2.2 인스턴스 관리자

오브젝트를 생성하는 과정에서 직접 대상 오브젝트의 인스턴스를 연결하고 관리하는 관리자를 두는 방법이다.

using UnityEngine;

public class TargetManager : MonoBehaviour
{
   public TargetObject targetObject;
   List<TargetObject> lists = new List<TargetObject>();
   public int count;
   
   // Start is called before the first frame update
   void Start()
   {
      CreateInstance();
   }
   
   void CreateInstance()
   {
     for(int i = 0; i < count; i++)
     {
        TargetObject target = Instantiate(targetObject);
        lists.Add(target);
     }
   }
   
   // Update is called once per frame 
   void Update()
   {
      for(int i = 0; i < lists.Count; i++)
      {
         Debug.Log(lists[i].index);
      }
   }
}


public class TargetObject : MonoBehaviour
{
   public int index;
}

 

 

2.3 Hierachy에서 찾기

GameObject는 GameObject의 계층 구조에서 쉽게 대상 오브젝트를 찾을 수 있도록 GetComponent() 함수를 제공한다.

GetComponent()는 유니티 프로젝트를 진행하다보면 자주 사용하게 되는 함수 중의 하나이다. GetComponent()는 단일 대상 오브젝트를 찾을 수 있으며, GetComponents() 함수는 여러 대상 오브젝트들을 찾을 수 있다. 계층 구조에서 부모의 컴포넌트를 찾을 수 있는 함수 (GetComponentInparent()), 하위 컴포넌트에서 대상 오브젝트를 찾을 수 있는 함수(GetComponentInChildren()) 도 있다. 컴포넌트에는 스크립트(Script :Class)도 포함된다. 

T t = GetComponent<T>();
Component component = GetComponent(typeof(T));

T[] ts = GetComponents<T>();
Component[] components = GetComponents(typeof(T));

T t = GetComponentInParent<T>();
Component component = GetComponentInParent(typeof(T));

T[] ts = GetComponentsInParent<T>();
Component[] components = GetComponentsInParent(typeof(T));

T t = GetComponentInChildren<T>();
Component component = GetComponentInChildren(typeof(T));

T[] ts = GetComponentsInChildren<T>();
Component[] components = GetComponentsInChildren(typeof(T));

 

using UnityEngine;

[RequireComponent(typeof(Collider))]
public class Test : MonoBehaviour
{
   void OnCollisionEnter(Collision collision)
   {
     Collider collider = collsion.collider;
     TestHit hit = collider.gameObject.GetComponent<TestHit>();
     Debug.Log(hit.hitName);
   }
   
   void OnCllisionExit(Collision collision)
   {
      Component[] components = collision.gameObject.GetComponents(typeof(TestHit));
      foreach(TestHit hit in components)
      {
         Debug.Log(hit.hitName);
      }
   }
   
   void OnTriggerEnter(Collider other)
   {
      TestHit hit = other.GetComponentInChildren(typeof(TestHit)) as TestHit;
      Debug.Log(hit.hitName);
   }
   
   void OnTriggerExit(Collider other)
   {
      TestHit[] hits = other.GetComponentsInChildren<TestHit>();
      for(int i = 0; i < hits.Length; i++)
      {
         Debug.Log(hits[i].hitName);
      }
   }
}

 

using UnityEngine;

[RequireComponent(typeof(Collider))]
public class TestHit : MonoBehaviour
{
   public string hitName;
}

 

 

3. 오브젝트 (Object)

오브젝트는 유니티의 최상위 클래스이며 유니티가 참조하는 모든 클래스의 기본 클래스이다. Base class for all objects Unity can reference. 유니티의 모든 개체는 Object를 상속받아 구현되기 때문에, 다음의 FindObjectOfType() 함수를 사용하여 접근할 수 있다. 

Object

 

3.1 Object.FindObjectOfType()

FindObjecOfType은 Object의 정적 함수이다.  FindObjectOfType은 기본적으로 활성화된 개체를 찾는다. 그러나 인수를 전달하면 비활성화된 개체를 찾을 수 있다. 

비활성화 활성화의 기준은 Inspector 창의 GameObject를 기준으로 한다. 

Active or Inactive

FindObjectOfType은 찾고자하는 타입의 처음으로 활성화된 개체를 찾는다.

FindObjecOfType

FindObjectOfType<T>();
FindObjectOfType<T>(bool includeinactive);
FindObjectOfType(typeof(T));
FindObjectOfType(typeof(T), bool includeinactive);

 

 

3.4 FindObjectOfType example

using UnityEngine;

public class TestFind : MonoBehaviour
{
   //Start is called before the first frame update
   void Start()
   {
      Camera camera = FindObjectOfType<Camera>();
      Camera camera = FindObjectOfType<Camera>(true);
      
      Object cameraObject = FindObjectOfType(typeof(Camera));
      Camera camera = cameraObject as Camera;
      
      Camera camera = FindObjectOfType(typeof(Camera)) as Camera;
      
      Object cameraObject = FindObjectOfType(typeof(Camera), true);
      Camera camera = cameraObject as Camera;
      
      Camera camera = FindObjectOfType(typeof(Camera), true) as Camera;
   }
}

    

 

4. GameObject

GameObject는 유니티 씬들(Scenes)에 존재하는 모든 개체의 기본 클래스이다. GameObject는 Find()함수를 제공한다. 이를 사용하면 대상 오브젝틀 찾을 수 있다.

 

4.1 GameObjec.Find()

Find() 함수는 오브젝트를 찾을 때 오브젝트의 이름으로 찾는다.

Find() 함수는 활성화된 오브젝트들을 검색하여 반환한다.

Find() 함수는 대상 오브젝트를 찾지 못하면 null을 반환한다.

매개 변수로 string 형식을 사용하며 대소문자를 구분한다.   

GameObject.Find(string Name);

 

Main Camera Name

 

4.2 GameObject.Find() example

using UnityEngine;

public class Finder : MonoBehaviour
{
   // Start is called before the first frame update
   void Start()
   {
      GameObject target = GameObject.Find("main Camera");
      Debug.Log(target); //Error
      GameObject target = GameObject.Find("Main Camera");
      Debug.Log(target);
   }

}

 

 

 

 

 

reference 

[1] https://learn.microsoft.com/ko-kr/dotnet/csharp/programming-guide/generics/generic-type-parameters

 

728x90
반응형