LoginSignup
5
5

More than 3 years have passed since last update.

[Unity] Prefabの編集をC#スクリプトで行う

Last updated at Posted at 2020-08-04

概要

タイトルの通り、Prefabとして固めてあるものをスクリプトで開いて、編集して、保存するための方法を書き記します。

方法

const string PrefabPath = "Assets/Prefabs/Player.prefab";
GameObject player = PrefabUtility.LoadPrefabContents(PrefabPath);

/*
 * 読み込んだPrefabの内容を変更
 */

PrefabUtility.SaveAsPrefabAsset(player, PrefabPath);
PrefabUtility.UnloadPrefabContents(player);

注意点

  • Prefabのパスはプロジェクトフォルダをルートとして指定します
  • 拡張子の.prefabまで入れないと読み込まれません
  • SaveAsPrefabAsset()で保存しないと、変更した内容が反映されません
  • UnloadPrefabContents()でアンロードすることを忘れずに

読み込んだ後

GameObject player = PrefabUtility.LoadPrefabContents(PrefabPath);

int count = player.childCount;  // 子要素の数
for(int i=0; i<count; i++)
{
    GameObject obj = player.GetChild(i);    // 子要素はインデックスで持ってこられる

    // なにかコンポーネントを持ってくるときはGetComponent()で
    var cinemachine = path.GetComponent<Cinemachine.CinemachineSmoothPath>();
}

UnityEditor上で

  • Hierarchyで操作するものはGameObject
  • Inspectorで操作するものはComponent

です(ここらへん不安なので信用しないように)。

以上です。

参考リンク

5
5
1

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