2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Unity: スクリプトだけで親子関係のあるオブジェクトを作成する

Posted at

 最近趣味でUnityを扱っていて、その中でスクリプト上でオブジェクトを作成し親子関係を設定することがあったのでまとめておきます。

親子関係のあるオブジェクトを作成する

 まず、スクリプトを作成します。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class sample : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

1. 3Dオブジェクトの作成

 3Dのオブジェクトを作成する際には、GameObject.CreatePrimiticve関数を使用するようです。その引数でオブジェクトのタイプを選択することでオブジェクトを出力します。


void Start()
{
    // プレーン型オブジェクト
    GameObject plane  = GameObject.CreatePrimitive(PrimitiveType.Plane);
    // キューブ型オブジェクト
    GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
    // 球型オブジェクト
    GameObject sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);
    // カプセル型オブジェクト
    GameObject capsule = GameObject.CreatePrimitive(PrimitiveType.Capsule);
    // 円柱型オブジェクト
    GameObject cylinder = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
}

2. オブジェクトの親子関係の追加

 親子関係はオブジェクトのtransform間に設定される関係なようで、子オブジェクトのtransformに対してparent要素に親オブジェクトのtransformを代入するだけで良いようです。

// キューブ型オブジェクトの親要素に球型オブジェクトを追加する
cube.transform.parent = sphere.transform;
// カプセル型オブジェクトの親要素に球型オブジェクトを追加する
capsule.transform.parent = sphere.transform;

親子関係の解消について

子オブジェクトから

 子オブジェクトからの親子関係の解消は子オブジェクトに登録されていた親オブジェクトを上書きすることでできます。

cube.transform.parent = null;

親オブジェクトから

 親オブジェクトからの親子関係の解消は複数の子オブジェクト全てとの親子関係を削除することになります。

sphere.transform.DetachChildren();
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?