0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Unity】RectTransformを持つ空のGameObjectをスクリプトから生成する

0
Posted at

空のGameObjectを生成と同時にRectTransformをtypeofを行う

void Start()
{
    //空のゲームオブジェクトを生成とアタッチを同時に行う
    var obj_0 = new GameObject("Empty_0", typeof(RectTransform));

    //これでも同じことができる
    var obj_1 = new GameObject("Empty_0", typeof(RectTransform));
    if (obj_1 != null)
    {
        obj_1.AddComponent<RectTransform>();
    }
}

エディタ画面
スクリーンショット 2026-03-08 020314.png

オーバーロードで第2引数が存在する場合の関数を見てみます

public GameObject(string name, params Type[] components)
{
    Internal_CreateGameObject(this, name);
    foreach (Type componentType in components)
    {
        AddComponent(componentType);
    }
}

内部でAddComponentを行っているため
だから、こうゆう書き方もできる


    void Start()
    {
        //アタッチしたいコンポーネント一覧
        var typeArray = new Type[5];
        typeArray[0] = typeof(RectTransform);
        typeArray[1] = typeof(Camera);
        typeArray[2] = typeof(Light);
        typeArray[3] = typeof(Rigidbody2D);
        typeArray[4] = typeof(EventSystem);

        var obj_2 = new GameObject("Empty_2", typeArray);
    }

スクリーンショット 2026-03-08 021136.png

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?