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 3 years have passed since last update.

【UnityEditor拡張】Transportなどのプロパティ値を変更して反映する

Last updated at Posted at 2020-08-17

概要

Unityのエディタ拡張などでオブジェクトの位置などを一括で設定したい!って場合のやり方を記載する。

やり方

void SetPosition(Vector3 pos)
{
    var obj = GameObject.Find("Player");
    obj.transform.position = pos;
}

これでPlayerゲームオブジェクトの位置を設定できた。…わけではない。

これをエディタ上で実行してもSceneビュー上だと確かに位置は動いているが、
変更された形跡もないし保存もできない、なぜだか変更した値が反映されていないというおかしな状態になってしまう。

正しいやり方

一旦、値を設定するtransformSerializedObjectに変換して値を変更する必要がある。

void SetPosition(Vector3 pos)
{
    var obj = GameObject.Find("Player");

    var serializedTransform = new SerializedObject(obj.transform);

    // オブジェクトの値を最新のものに更新
    serializedTransform.Update();

    // 位置を示すプロパティ名はm_LocalPosition
    // 型はVector3なので.vector3Valueに代入
    serializedTransform.FindProperty("m_LocalPosition").vector3Value = pos;
    
    // 変更した値を適用
    serializedTransform.ApplyModifiedProperties();
}

上記のようにして変更する。
すると、値はしっかりと変更され、Hierarchyビューでも変更を示すマークが付く。もちろんUndoも可能になる。

プロパティ名の調べ方

プロパティ名は、以下のようにすると一覧が取得できる。

var iterator = serializedObject.GetIterator();
while (iterator.NextVisible(true)){
    Debug.Log (iterator.propertyPath);
}

下記のリンク先の丸パクリですみません……。

参考リンク

以下の記事を参考にさせていただきました。

以上です。

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?