うにてぃブログ

主にUnityとC#に関する記事を書いていきます

【Unity】PrefabMode でスクリプトからオブジェクトを選択状態にする

Hierarchy にあるオブジェクトを選択状態にするには

GameObject.Find でパスからオブジェクトを探して、Selection.activeGameObjectに代入するだけでできる

Selection.activeGameObject = GameObject.Find(path);

しかし、PrefabMode の場合 GameObject.Find でパスを指定しても探すことができない

そのため、PrefabStageUtility を利用してオブジェクトを探しだす必要がある

// 現在のPrefabMode の Stage を取得
var stage = PrefabStageUtility.GetCurrentPrefabStage();
 
// Root のオブジェクトを取得
var root = stage.prefabContentsRoot;
 
// パスに Root オブジェクト が含まれているので削除
var index = path.IndexOf("/") + 1;
path = path.Substring(index);
 
// root からパスを辿る
var findChild = root.transform.Find(path);
 
// 見つけたオブジェクトを代入
Selection.activeGameObject = findChild.gameObject;