【Unity】名前を指定せずにスクリプトを取得する

投稿者: | 2020-12-06

空のオブジェクトにスクリプトをつけました。別のオブジェクトに新しいスクリプトをつけて、こちらに上のオブジェクトをアタッチしました。

このスクリプトで、コンポーネントを取得するときに、型引数にMonoBehaviourと入れてもはじめのスクリプトを取得できました。

  1. using UnityEngine;
  2.  
  3. public class GetComponent : MonoBehaviour
  4. {
  5. [SerializeField] GameObject obj;
  6.  
  7. // Start is called before the first frame update
  8. void Start()
  9. {
  10. var sc = obj.GetComponent<MonoBehaviour>();
  11. Debug.Log(sc.GetType());
  12. }
  13.  
  14. }

スクリプトが複数あっても問題ありません。

  1. using UnityEngine;
  2.  
  3. public class GetComponent : MonoBehaviour
  4. {
  5. [SerializeField] GameObject obj;
  6.  
  7. // Start is called before the first frame update
  8. void Start()
  9. {
  10. var sc = obj.GetComponents<MonoBehaviour>();
  11. Debug.Log(sc[0].GetType());
  12. Debug.Log(sc[1].GetType());
  13. }
  14.  
  15. }

コメントを残す

メールアドレスが公開されることはありません。