LoginSignup
0
1

Unity で Prefab にアタッチされたコンポーネントが Find できないんですが?

Last updated at Posted at 2021-11-21

と思ってましたが、以下の記事のコードをコピペすると、ちゃんと動きます。
色々書いてありますが、個人的に必要なのは1行だけでした。


自分は今まで、以下のようなコードを書いていました。

MyOriginalComponent[] nodes = FindObjectsOfType<MyOriginalComponent>();

cf. https://docs.unity3d.com/2021.3/Documentation/ScriptReference/Object.FindObjectsOfType.html

これは、冒頭の記事の方法を採用すると以下のように書けます。

- MyOriginalComponent[] nodes = FindObjectsOfType<MyOriginalComponent>();
+ MyOriginalComponent[] nodes = FindObjectsOfType(typeof(MyOriginalComponent)) as MyOriginalComponent[];

オブジェクトであれば検索に引っかかるらしく、それを変換して代入するわけですね。
その発想はなかった。

ちなみに、FindObjectsOfType() の説明に、

This does not return assets (such as meshes, textures or prefabs), or objects with HideFlags.DontSave set. Objects attached to inactive GameObjects are only included if inactiveObjects is set to true. Use Resources.FindObjectsOfTypeAll to avoid these limitations.

Google 翻訳:
これは、アセット (メッシュ、テクスチャ、プレハブなど) や HideFlags.DontSave が設定されたオブジェクトを返しません。非アクティブなゲームオブジェクトにアタッチされたオブジェクトは、inactiveObjects が true に設定されている場合にのみ含まれます。これらの制限を回避するには、Resources.FindObjectsOfTypeAll を使用します。

とあります。

つまり非アクティブなオブジェクトも探す場合は、以下の書き方になります。

- MyOriginalComponent[] nodes = FindObjectsOfType(typeof(MyOriginalComponent)) as MyOriginalComponent[];
+ MyOriginalComponent[] nodes = Resources.FindObjectsOfTypeAll(typeof(MyOriginalComponent)) as MyOriginalComponent[]

cf. https://docs.unity3d.com/2021.3/Documentation/ScriptReference/Resources.FindObjectsOfTypeAll.html

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