1
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?

More than 1 year has passed since last update.

new Transform() したい

Last updated at Posted at 2023-08-31

Unityで、new Transform()したくなる時ってありませんか?
目的としては、たとえば

for (int y = 0; y < ty; ++y)
{
    for(int x = 0; x < tx; ++x)
    {
        GameObject go = GameObject.CreatePrimitive(PrimitiveType.cube);
        Transform tr = GetRotAndPos(x, y);
        go.transform.position = tr;
    }
}

のように、新しいtransformのインスタンスを作って渡したい、などです。
残念ながらnew Transform()はできませんが、いくつか方法があります。

Transform tr = new GameObject().transform;
でgameObjectを作って、値を渡して不要になったDestroy()する、というパワープレイはとりあえずやめておいたほうがよさそうです。

多くの場合、Transformのインスタンスが欲しい={Vector3,Quaternion}のセットを作って渡したいだけ、ではないかと思います。
{Vector3,Quaternion}の構造体を作って使用することもできますが、
無名構造体のような感じでタプルを使うこともできます。

    (Vector3 pos, Quaternion rot) tr = GetGeoPanelPos(x, y);
    go.transform.position = tr.pos;
    go.transform.rotation = tr.rot;

(Vector3 pos, Quaternion rot) GetGeoPanelPos(int _x, int _y)
{
    float rx = (float)_x * 4f;
    float ry = (float)_y * 4f;
    Quaternion rot = Quaternion.Euler(ry, rx, 0f);
    Vector3 pos = rot * -Vector3.forward * 10f;
    return (pos,rot);
}

または、上記の例のような場合は、GameObjectをInstantiateした後にGetRotAndPos()しても良いわけなので、

    GameObject go = GameObject.CreatePrimitive(PrimitiveType.cube);
    SetRotAndPos(ref go, x, y);

のように参照渡しを介してgo.transformに値を入れてしまうこともできます。

void SetGeoPanelPos(ref GameObject _go, int _x, int _y)
{
    float rx = (float)_x * 4f;
    float ry = (float)_y * 4f;
    _go.transform.rotation = Quaternion.Euler(ry, rx, 0f);
    _go.transform.position = _go.transform.rotation * -Vector3.forward * 10f;
}

他にもあれば教えてください。

1
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
1
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?