-
-
Save todorok1/315d6c0cf53e2d9ccdd182ada59e20bb to your computer and use it in GitHub Desktop.
FindObjectsByTypeでまとめて取得
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using UnityEngine; | |
| using System.Linq; | |
| public class FindAnyTest : MonoBehaviour | |
| { | |
| void Start() | |
| { | |
| // それぞれのShowMessage()を呼び出してみると…… | |
| var pikachu = FindAnyObjectByType<BasePikachu>(); | |
| pikachu.ShowMessage(); | |
| var raichu = FindAnyObjectByType<DerivedRaichu>(); | |
| raichu.ShowMessage(); | |
| // 指定した型のコンポーネントをまとめて取得 | |
| var pikachus = FindObjectsByType<BasePikachu>(FindObjectsSortMode.None); | |
| // foreach文で対象を取得 | |
| foreach (var p in pikachus) | |
| { | |
| if (p.GetType() == typeof(BasePikachu)) | |
| { | |
| p.ShowMessage(); | |
| break; | |
| } | |
| } | |
| // こちらはLinqで取得 | |
| var pikachu2 = pikachus.Where(p => p.GetType() == typeof(BasePikachu)) | |
| .FirstOrDefault(); | |
| pikachu2.ShowMessage(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment