Version: 2022.1
언어: 한국어
중요 클래스
중요 클래스 - MonoBehaviour

중요 클래스 - GameObject

Unity’s GameObject class represents anything which can exist in a Scene.

이 페이지는 Unity의 GameObject 클래스를 사용하는 스크립팅과 관련이 있습니다. Unity 에디터의 씬 및 계층 구조에서 게임 오브젝트를 사용하는 방법은 사용자 매뉴얼의 게임 오브젝트 섹션을 참조하십시오. GameObject 클래스의 모든 멤버에 대한 전체 레퍼런스는 게임 오브젝트 스크립트 레퍼런스를 참조하십시오.

게임 오브젝트는 Unity의 씬을 위한 빌딩 블록이며, 게임 오브젝트의 모양과 게임 오브젝트의 기능을 결정하는 기능적 컴포넌트의 컨테이너 역할을 합니다.

In scripting, the GameObject class provides a collection of methods which allow you to work with them in your code, including finding, making connections and sending messages between GameObjects, and adding or removing components attached to the GameObject, and setting values relating to their status within the scene.

씬 상태 프로퍼티

You can use scripts to modify many properties related to a GameObject’s status in the scene. These typically correspond to the controls visible near the top of the inspector when you have a GameObject selected in the Editor.

이 컨트롤은 특정 컴포넌트와 관련이 없으며 상단의 게임 오브젝트 인스펙터에서 컴포넌트 리스트 위에 표시됩니다.

인스펙터에 표시되는 일반적인 게임 오브젝트로, 이 경우에는 방향 광원입니다. 씬 상태 프로퍼티에 빨간색 테두리가 있습니다.
인스펙터에 표시되는 일반적인 게임 오브젝트로, 이 경우에는 방향 광원입니다. 씬 상태 프로퍼티에 빨간색 테두리가 있습니다.

모든 게임 오브젝트는 씬 내 게임 오브젝트 상태와 관련하여 인스펙터 상단의 컨트롤 세트를 공유하며, 게임 오브젝트의 스크립팅 API를 통해 제어할 수 있습니다.

GameObject 클래스에 대해 사용할 수 있는 간단한 API 리스트는 게임 오브젝트 스크립트 레퍼런스를 참조하십시오.

활성 상태

게임 오브젝트의 활성 상태
게임 오브젝트의 활성 상태

게임 오브젝트는 기본적으로 활성 상태이지만, 비활성화하여 게임 오브젝트에 연결된 모든 컴포넌트를 해제할 수 있습니다. 일반적으로 비활성 게임 오브젝트는 눈에 보이지 않고 Update 또는 FixedUpdate 등과 같은 정상적인 콜백이나 이벤트를 수신하지 않습니다.

게임 오브젝트의 활성 상태는 게임 오브젝트 이름 왼쪽의 체크박스로 표시되며, GameObject.SetActive를 사용하여 제어할 수 있습니다.

You can also use GameObject.activeSelf to read the current active state of a GameObject. Use GameObject.activeInHierarchy to read whether the GameObject is actually active in the scene. GameObject.activeInHierarchy is necessary because whether a GameObject is actually active is determined by its own active state and the active state of all of its parents. If any of its parents aren’t active, then it’s not active despite its own active setting.

정적 상태

게임 오브젝트의 정적 상태
게임 오브젝트의 정적 상태

전역 조명, 오클루전, 배칭, 내비게이션, 반사 프로브와 같은 일부 Unity 시스템은 게임 오브젝트의 정적 상태에 의존합니다. GameObjectUtility.SetStaticEditorFlags를 사용하여 게임 오브젝트를 정적으로 간주하는 Unity 시스템을 제어할 수 있습니다. 여기에서 정적 게임 오브젝트에 대해 자세히 알아보십시오.

태그 및 레이어

The Tag and Layer fields of a GameObject
The Tag and Layer fields of a GameObject

태그는 씬에서 게임 오브젝트 타입을 표시 및 식별하는 방식을 제공하고, 레이어렌더링 또는 물리 충돌 같은 특정 빌트인 동작에 게임 오브젝트 그룹을 포함하거나 제외하는 유사하면서도 차별화되는 방식을 제공합니다.

에디터에서 태그와 레이어를 사용하는 방법은 메인 사용자 매뉴얼 페이지에서 태그레이어를 참조하십시오.

You can modify tag and layer values via script using the GameObject.tag and GameObject.layer properties. You can also check a GameObject’s tag efficiently by using the CompareTag method, which includes validation of whether the tag exists, and doesn’t cause any memory allocation.

컴포넌트 추가 및 제거

런타임 시점에 컴포넌트를 추가하거나 제거할 수 있으며, 이는 게임 오브젝트를 절차적으로 생성하거나 게임 오브젝트의 동작 방식을 수정할 때 유용합니다. 또한 손상을 일으키지 않고 스크립트를 통해 스크립트 컴포넌트와 일부 타입의 빌트인 컴포넌트를 enable 또는 disable 상태로 만들 수 있습니다.

런타임 시점에 컴포넌트를 추가하는 가장 좋은 방법은 AddComponent<Type>를 사용하여 여기에 보이는 것처럼 컴포넌트 타입을 꺾쇠 괄호 안에 지정하는 것입니다. 컴포넌트를 제거하려면 컴포넌트 자체에 대해 Object.Destroy 메서드를 사용해야 합니다.

컴포넌트 액세스

가장 간단한 예로는 게임 오브젝트의 스크립트가 동일한 게임 오브젝트에 연결된 다른 컴포넌트에 액세스해야 하는 경우를 들 수 있습니다(게임 오브젝트에 연결된 다른 스크립트도 컴포넌트 자체라는 점에 유의해야 함). 이렇게 하려면 사용하려는 컴포넌트 인스턴스에 대한 레퍼런스를 먼저 가져와야 합니다. 이때 GetComponent 메서드가 사용됩니다. 일반적으로 컴포넌트 오브젝트를 변수에 할당해야 하며, 이는 다음 코드를 통해 수행할 수 있습니다. 다음 예제에서 스크립트는 동일한 게임 오브젝트의 리지드바디 컴포넌트에 대한 레퍼런스를 가져옵니다.

void Start ()
{
    Rigidbody rb = GetComponent<Rigidbody>();
}

컴포넌트 인스턴스에 대한 레퍼런스가 있으면 인스펙터에서와 마찬가지로 프로퍼티 값을 설정할 수 있습니다.

void Start ()
{
    Rigidbody rb = GetComponent<Rigidbody>();

    // Change the mass of the object's Rigidbody.
    rb.mass = 10f;
}

다음과 같이 컴포넌트 레퍼런스에 대한 메서드를 호출할 수도 있습니다.

void Start ()
{
    Rigidbody rb = GetComponent<Rigidbody>();

    // Add a force to the Rigidbody.
    rb.AddForce(Vector3.up * 10f);
}

참고: 동일한 게임 오브젝트에 여러 개의 커스텀 스크립트를 연결할 수 있습니다. 한 스크립트에서 다른 스크립트에 액세스해야 할 때에는 평소와 마찬가지로 GetComponent를 사용하고 스크립트 클래스의 이름(또는 파일 이름)을 사용하여 원하는 컴포넌트 타입을 지정할 수 있습니다.

게임 오브젝트에 추가되지 않은 컴포넌트 타입을 검색하여 가져오려고 하면 GetComponent는 null을 반환합니다. null 오브젝트의 값을 변경하려는 모든 시도는 런타임 시점에 null 레퍼런스 오류를 발생시킵니다.

다른 게임 오브젝트의 컴포넌트 액세스

Although they sometimes operate in isolation, it’s common for scripts to keep track of other GameObjects, or more commonly, components on other GameObjects. For example, in a cooking game, a chef might need to know the position of the stove. Unity provides a number of different ways to retrieve other objects, each appropriate to certain situations.

인스펙터에서 게임 오브젝트를 변수에 연결

관련된 게임 오브젝트를 찾는 가장 간단한 방법은 public GameObject 변수를 스크립트에 추가하는 것입니다.

public class Chef : MonoBehaviour
{
    public GameObject stove;

    // Other variables and functions...
}

이 변수는 인스펙터에서 GameObject 필드로 표시됩니다.

씬 또는 계층 구조 패널에서 오브젝트를 이 변수로 드래그하여 할당할 수 있습니다.

프리팹을 프로젝트 창에서 인스펙터 창의 GameObject 필드로 드래그
프리팹을 프로젝트 창에서 인스펙터 창의 GameObject 필드로 드래그

GetComponent 함수와 컴포넌트 액세스 변수는 다른 요소와 마찬가지로 이 오브젝트에 이용할 수 있습니다. 따라서 다음과 같은 코드를 사용할 수 있습니다.

public class Chef : MonoBehaviour {

    public GameObject stove;

    void Start() {
        // Start the chef 2 units in front of the stove.
        transform.position = stove.transform.position + Vector3.forward * 2f;
    }
}

또한 스크립트에서 컴포넌트 타입의 public 변수를 선언하면 해당 컴포넌트가 연결된 게임 오브젝트를 드래그할 수 있습니다. 이렇게 하면 게임 오브젝트 자체가 아닌 컴포넌트에 직접 액세스합니다.

public Transform playerTransform;

Linking objects together with variables is most useful when you are dealing with individual objects that have permanent connections. You can use an array variable to link several objects of the same type, but the connections must still be made in the Unity editor rather than at runtime. It’s often convenient to locate objects at runtime and Unity provides two basic ways to do this, as described below.

자식 게임 오브젝트 찾기

Sometimes, a game Scene makes use of a number of GameObjects of the same type, such as collectibles, waypoints and obstacles. These might need to be tracked by a particular script that supervises or reacts to them (for example, all waypoints might need to be available to a pathfinding script). Using variables to link these GameObjects is a possibility but it makes the design process tedious if each new waypoint has to be dragged to a variable on a script. Likewise, if a waypoint is deleted, then it’s a nuisance to have to remove the variable reference to the missing GameObject. In cases like this, it is often better to manage a set of GameObjects by making them all children of one parent GameObject. The child GameObjects can be retrieved using the parent’s Transform component (because all GameObjects implicitly have a Transform):

using UnityEngine;

public class WaypointManager : MonoBehaviour {
    public Transform[] waypoints;

    void Start()
    {
        waypoints = new Transform[transform.childCount];
        int i = 0;

        foreach (Transform t in transform)
        {
            waypoints[i++] = t;
        }
    }
}

또한 Transform.Find 메서드를 사용하여 이름별로 특정 자식 오브젝트를 찾을 수 있습니다. transform.Find("Frying Pan");

게임플레이 중에 자식 게임 오브젝트가 추가되거나 제거되는 게임 오브젝트가 있을 때 유용합니다. 게임 플레이 중에 집어 들었다가 내려 놓을 수 있는 기구를 예로 들 수 있습니다.

메시지 전송 및 브로드캐스트

While editing your project you can set up references between GameObjects in the Inspector. However, sometimes it’s impossible to set up these in advance (for example, finding the nearest item to a character in your game, or making references to GameObjects that were instantiated after the Scene loaded). In these cases, you can find references and send messages between GameObjects at runtime.

BroadcastMessage를 사용하면 해당 메서드를 구현해야 하는 위치를 구체적으로 지정하지 않고도 명명된 메서드를 호출할 수 있습니다. 특정 게임 오브젝트 또는 그 자식 게임 오브젝트의 모든 MonoBehaviour에 대해 명명된 메서드를 호출할 수도 있습니다. 원하는 경우 최소 하나의 리시버가 존재하고 그렇지 않으면 오류가 생성되도록 지정할 수도 있습니다.

SendMessage는 좀더 특정적이며, 게임 오브젝트 자체(자식 제외)에 대해 명명된 메서드만 호출합니다.

SendMessageUpwards는 다소 유사하지만, 게임 오브젝트와 모든 해당 부모 에 대해 명명된 메서드를 호출합니다.

이름이나 태그로 게임 오브젝트 찾기

It’s always possible to locate GameObjects anywhere in the Scene hierarchy as long as you have some information to identify them. Individual objects can be retrieved by name using the GameObject.Find function:

GameObject player;

void Start()
{
    player = GameObject.Find("MainHeroCharacter");
}

오브젝트 또는 오브젝트 컬렉션은 GameObject.FindWithTagGameObject.FindGameObjectsWithTag 메서드를 사용하여 태그로도 찾을 수 있습니다.

다음은 한 명의 요리사 캐릭터가 등장하는 요리 게임에서 주방에 여러 개의 스토브(각각 “Stove” 태그 지정)가 있는 경우입니다.

GameObject chef;
GameObject[] stoves;

void Start()
{
    chef = GameObject.FindWithTag("Chef");
    stoves = GameObject.FindGameObjectsWithTag("Stove");
}

게임 오브젝트 생성 및 제거

프로젝트가 실행되는 동안 게임 오브젝트를 생성 및 제거할 수 있습니다. Unity에서 게임 오브젝트는 Instantiate 메서드를 사용하여 생성할 수 있습니다. 이 메서드는 기존 오브젝트의 새 복사본을 만듭니다.

게임 오브젝트를 인스턴스화하는 방법에 대한 전체 설명과 예제는 런타임 시점에 프리팹 인스턴스화를 참조하십시오.

The Destroy method destroys an object after the frame update has finished or optionally after a short time delay:

void OnCollisionEnter(Collision otherObj) {
    if (otherObj.gameObject.tag == "Garbage can") {
        Destroy(gameObject, 0.5f);
    }
}

Note that the Destroy function can destroy individual components and not affect the GameObject itself. A common mistake is to write this and assume it destroys the GameObject the script is attached to:

 Destroy(this);

this represents the script, and not the GameObject. It will actually just destroy the script component that calls it and leave the GameObject intact but with the script component removed.

프리미티브

GameObject 클래스는 Unity 게임 오브젝트 메뉴에서 제공되는 옵션에 대한 스크립트 기반 대안을 제공하며, 이를 통해 프리미티브 오브젝트를 만들 수 있습니다.

Unity의 빌트인 프리미티브 인스턴스를 생성하려면 지정된 타입의 프리미티브를 인스턴스화하는 GameObject.CreatePrimitive를 사용하십시오. 이용 가능한 프리미티브 타입은 구체, 캡슐, 실린더, 큐브, 평면사각형입니다.

Unity의 게임 오브젝트 메뉴에서 제공되는 프리미티브 셰이프
Unity의 게임 오브젝트 메뉴에서 제공되는 프리미티브 셰이프
중요 클래스
중요 클래스 - MonoBehaviour
Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。
公安部备案号:
31010902002961