---
title: ゲームオブジェクトとコンポーネント
slug: world-sdk-guide-ja/NG1y-60pq-CVpPfAeKdF2
docTags: 
createdAt: 2024-09-02T08:34:13.135Z
---

世界では、オブジェクトを作成したり、特定のコンポーネントをオブジェクトに変更または追加することが非常に一般的です。

ZEPETOScriptは、Unityスクリプトで使用されるのと同じインターフェースをサポートしています。

## GameObjectとComponentの基本例

ゲームオブジェクトの作成と削除：

:::CodeblockTabs
GameObject

```typescript
// GameObject 作成
const tempObj = new GameObject();
const obj = Object.Instantiate(tempObj);
 
// GameObject 削除
Object.Destroy(obj);
```
:::

GameObjectsのコンポーネントを取得したり、新しいものを追加するには、GetComponentまたはAddComponentを使用します。

:::CodeblockTabs
Component

```typescript
// ジェネリックを使用したGetComponent
const myTransform = this.GetComponent<Transform>();
 
// ジェネリックを使用したAddComponent
const animator = this.gameObject.AddComponent<Animator>();
```
:::



GameObject Componentの完全なコード例を確認してください。

こちらは、GameObjectの作成とプロパティの変更、コンポーネントの追加、破壊をカバーする例です。

:::CodeblockTabs
GameObjectSample

```typescript
import { GameObject, Object, Transform, Animator, Vector3, WaitForSeconds } from 'UnityEngine';
import { ZepetoScriptBehaviour } from 'ZEPETO.Script';
 
export default class GameObjectSample extends ZepetoScriptBehaviour {
 
    private _testObject : GameObject;
 
    Start() {
 
        // 空のGameObjectを作成
        const tempObj = new GameObject();
        this._testObject = Object.Instantiate(tempObj) as GameObject;
 
        // オブジェクトの名前を変更
        this._testObject.name = "TestObject";
 
        // オブジェクトの変換情報を変更
        this._testObject.transform.position = new Vector3(3,3,3);
 
        // オブジェクトにコンポーネントを追加
        this._testObject.gameObject.AddComponent<Animator>();
 
        // GetComponentの使用例
        const animator = this._testObject.GetComponent<Animator>();
        if(animator != null) {
            console.log("GetComponent 成功");
        }
 
        // コルーチンを使用して5秒後にオブジェクトを削除
        this.StartCoroutine(this.DestroyObject());
 
    }
 
    *DestroyObject() {
        yield new WaitForSeconds(5);
 
        // GameObjectを削除
        Object.Destroy(this._testObject);
    }
}  
```
:::



## Findの活用

Find関連メソッドは、Unityスクリプトと同様にZEPETOScriptで同じインターフェーススタイルをサポートしています。

| メソッド                                | 説明                                                                                                                        |
| ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
| GameObject.Find()                   | - 現在のシーン内の名前に基づいてアクティブなGameObjectオブジェクトを見つけて返します。<br />- 見つからない場合はnullを返します。                                              |
| GameObject.FindGameObjectWithTag()  | - 現在のシーン内のタグに基づいてアクティブなGameObjectオブジェクトを見つけて返します。<br />- アクティブなオブジェクトの中から指定されたタグに一致する最初のオブジェクトを見つけて返し、見つからない場合はnullを返します。 |
| GameObject.FindGameObjectsWithTag() | - 現在のシーン内の特定のタグを持つすべてのアクティブなGameObjectオブジェクトを見つけて配列として返します。<br />- 見つからない場合は空の配列を返します。                                    |

例として、シーンを次のように設定します：

- いくつかの3Dオブジェクトを追加し、すべてのタグを3Dとして指定します。
- スクリプトをアタッチするための空のオブジェクトを作成し、それをFindSampleに名前変更します。

![](https://api.archbee.com/api/optimize/fCt3n1oCa8rgNJ8fw9I2N-zzyzWZyF_39SRWiOi4pqT-20240904-102427.png)



:::CodeblockTabs
TypeScript

```typescript
import { ZepetoScriptBehaviour } from 'ZEPETO.Script';
import { GameObject, Transform } from 'UnityEngine';

export default class FindSample extends ZepetoScriptBehaviour {

    public tempObj1: GameObject;
    public tempObj2: GameObject;
    public tempObj3: GameObject[];

    Start() {    
        // 指定された名前のターゲットGameObjectを見つけます。
        // 同じ名前のGameObjectが複数ある場合、最初に見つかったものが返されます。
        this.tempObj1 = GameObject.Find("Cube");
        if(this.tempObj1 != null) {
            console.log("GameObjectの検索成功");
        }
 
        // 指定されたタグのターゲットGameObjectを見つけます。
        // 同じタグのGameObjectが複数ある場合、最初に見つかったものが返されます。
        this.tempObj2 = GameObject.FindGameObjectWithTag("3D");
        if(this.tempObj2 != null) {
            console.log("FindGameObjectWithTagの成功");
        }
 
        // 指定されたタグを持つGameObjectの配列を返します。
        this.tempObj3 = GameObject.FindGameObjectsWithTag("3D");
        if(this.tempObj3 != null) {
            console.log("FindGameObjectsWithTagの成功");
        }
    }
}
```
:::



- FindSampleオブジェクトにスクリプトを追加すると、インスペクタは空になります。

::Image[]{src="https://api.archbee.com/api/optimize/fCt3n1oCa8rgNJ8fw9I2N-brkQtTPkzO4PVeCeTWY0C-20240904-102427.png" size="66" width="484" height="554" position="center" showCaption="false"}



- 再生ボタンを押して実行し、インスペクタウィンドウで各オブジェクトが割り当てられていることを確認し、コンソールウィンドウを通じてオブジェクトの検索成功を確認できます。

![](https://api.archbee.com/api/optimize/fCt3n1oCa8rgNJ8fw9I2N-v0TXlzool-ExIjeoQtL2q-20240904-102427.png)

## プレハブの作成

ランタイム中にプレハブを作成する方法を探ってみましょう。

- まず、3Dオブジェクト > キューブをシーンに追加します。

::Image[]{src="https://api.archbee.com/api/optimize/fCt3n1oCa8rgNJ8fw9I2N-n8sQHSZS0g09ODQKdPMFn-20240904-102428.png" size="50" width="592" height="742" position="center" showCaption="false"}



- キューブのインスペクターで「コンポーネントを追加」を押し、Rigidbodyを追加します。

![](https://api.archbee.com/api/optimize/fCt3n1oCa8rgNJ8fw9I2N-uQQEDtu2B7HHrZZa09X1K-20240904-102428.png)



- 次に、キューブをプロジェクトエリアにドラッグしてプレハブにします。

::Image[]{src="https://api.archbee.com/api/optimize/fCt3n1oCa8rgNJ8fw9I2N-mzQZpGo5GJ00sZShBiWbC-20240904-102428.png" size="88" width="367" height="397" position="center" showCaption="false"}



- プレハブを利用するため、シーン内のキューブを削除します。



  ::Image[]{src="https://api.archbee.com/api/optimize/fCt3n1oCa8rgNJ8fw9I2N-YGeJYJrbHhKghMigpQObo-20240904-102428.png" size="62" width="326" height="327" position="center" showCaption="false"}

- 以下のスクリプトを書いてください。

:::CodeblockTabs
TypeScript

```typescript
import { GameObject, Object, Vector3, WaitForSeconds } from 'UnityEngine';
import { ZepetoScriptBehaviour } from 'ZEPETO.Script';
 
export default class CloneSample extends ZepetoScriptBehaviour {
     
    public clonePrefab : GameObject;
 
    Start() {
 
        this.StartCoroutine(this.DoRoutine());
 
    }
 
    *DoRoutine() {
        while(true) {
            yield null;
            // Create a clone
            const clone = Object.Instantiate(this.clonePrefab) as GameObject;
             
            // Set the height of the clone object
            clone.transform.position = new Vector3(0, 10, 0);
             
            // Destroy it after 5 seconds of creation
            GameObject.Destroy(clone, 5);
            yield new WaitForSeconds(1);
        }
    }
}

```
:::

- 次に、Unityエディタに戻り、プレハブをスクリプトインスペクタにドラッグして追加します。

![](https://api.archbee.com/api/optimize/fCt3n1oCa8rgNJ8fw9I2N-ZwlrtxyGBbAFEh2eKJeg--20240904-102428.png)



- 再生ボタンを押して、3Dオブジェクトが作成され、毎秒上から落ちてくることを確認します。

![](https://api.archbee.com/api/optimize/fCt3n1oCa8rgNJ8fw9I2N-WsJD59NBM4Q9x0R_24yiH-20240904-102428.gif)

以下のリンクをクリックして、ZEPETOScriptが提供するUnityのGameObjectsとComponentsについて詳しく学んでください。



:::hint{type="info"}
**📘 GameObjectsの作成**
[https://docs.unity3d.com/2020.3/Documentation/ScriptReference/Object.Instantiate.html](https://docs.unity3d.com/2020.3/Documentation/ScriptReference/Object.Instantiate.html)
:::

:::hint{type="info"}
**📘 GameObjectsの破壊**
[https://docs.unity3d.com/2020.3/Documentation/ScriptReference/Object.Destroy.html](https://docs.unity3d.com/2020.3/Documentation/ScriptReference/Object.Destroy.html)
:::

:::hint{type="info"}
**📘 コンポーネントの使用**
[https://docs.unity3d.com/kr/current/Manual/UsingComponents.html](https://docs.unity3d.com/kr/current/Manual/UsingComponents.html)
:::

