首页 > 解决方案 > GetComponent 要求请求的组件 'AudioSource[]' 派生自 MonoBehaviour 或 Component 或者是一个接口

问题描述

我实现了 IBM Watson 的 Speech-to-Text,所以当我说“jump”/“anger”时,我的角色会播放一个音频剪辑。但是我收到了这个错误,这会阻止角色对我的语音触发器做出反应。

错误信息:

Unity Exception ArgumentException: GetComponent requires that the requested component 'AudioSource[]' derives from MonoBehaviour or Component or is an interface.

我的 CharacterController.cs:

   using UnityEngine;

    public class CharacterController : MonoBehaviour
    {

        // Use this for initialization

        public Animator anim;

        public AudioSource[] _audio;

        void Start()
        {

        }

        // Update is called once per frame
        void Update()
        {

            anim = GetComponent<Animator>();
            _audio = GetComponent<AudioSource[]>();
        }

        public void CharacterActions(string ActionCommands)
        {
            ActionCommands = ActionCommands.Trim();
            switch (ActionCommands)
            {
                case "jump":
                    anim.Play("jump", -1, 0f);
                    _audio[0].Play();
                    break;
                case "anger":
                    anim.Play("rage", -1, 0f);
                    _audio[1].Play();
                    break;

                default:
                    anim.Play("idle", -1, 0f);
                    break;

            }


        }
    }

标签: unity3dspeech-to-text

解决方案


您不能使用GetComponent获取所有AudioSource对象的数组,因为 Unity 将搜索具有类型AudioSource[]而不是 的组件AudioSource,这些组件不存在。要获取AudioSource您必须做的所有对象的数组

_audio = GetComponents<AudioSource>();

反而。


推荐阅读