Skip to content

Instantly share code, notes, and snippets.

@todorok1
Created January 22, 2026 09:02
Show Gist options
  • Select an option

  • Save todorok1/315d6c0cf53e2d9ccdd182ada59e20bb to your computer and use it in GitHub Desktop.

Select an option

Save todorok1/315d6c0cf53e2d9ccdd182ada59e20bb to your computer and use it in GitHub Desktop.
FindObjectsByTypeでまとめて取得
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