【问题标题】:'AudioSource' does not contain a definition for 'PlayOneShot' in Unity“AudioSource”不包含 Unity 中“PlayOneShot”的定义
【发布时间】:2021-11-19 12:18:41
【问题描述】:

我在 Unity 项目中创建了一个带有 AudioSource 组件的 GameObject。我相信我已经正确地使用了 GetComponent 函数来访问所述组件。我正在尝试通过脚本使用 PlayOneShot() 函数,但它无法编译。我正在使用 Unity 2020.3.22f1 (LTS) 和 Visual Studio for Mac 8.10.14。

Unity 包文件链接:https://1drv.ms/u/s!AvhOYSsJUBS1hUocvPEgfmkwHfeh

脚本:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Ball : MonoBehaviour
{

    // Configuration Parameters
    [SerializeField] Paddle paddle1;
    [SerializeField] float xPush = 2f, yPush = 10f;
    [SerializeField] AudioClip[] ballSounds;
    [SerializeField] float randomFactor = 0.2f;

    // state
    Vector3 paddleToBallVector;
    [SerializeField] bool hasStarted = false;

    // Cached component references
    [SerializeField] AudioSource audioSource;
    Rigidbody2D myRigidBody2D;

    // Start is called before the first frame update
    void Start()
    {
        paddleToBallVector = transform.position - paddle1.transform.position;
        audioSource = GetComponent<AudioSource>();
        myRigidBody2D = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        if (!hasStarted)
        {
            LaunchOnMouseClick();
            LockBallToPaddle();
        }

    }

    private void LaunchOnMouseClick()
    {
        if (Input.GetMouseButtonDown(0))
        {
            hasStarted = true;
            myRigidBody2D.velocity = new Vector2(xPush, yPush);
        }
    }

    private void LockBallToPaddle()
    {
        Vector3 ballPos = new Vector3(paddle1.transform.position.x, paddle1.transform.position.y, 1f);
        transform.position = ballPos + paddleToBallVector;
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        Vector2 velocityTweak = new Vector2
            (Random.Range(0f, randomFactor),
            Random.Range(0f, randomFactor));

        if (hasStarted)
        {
            AudioClip clip = ballSounds[UnityEngine.Random.Range(0, ballSounds.Length)];
            audioSource.PlayOneShot(clip);
            myRigidBody2D.velocity += velocityTweak;
        }
    }
}

【问题讨论】:

  • 嗯,当您输入“audioSource”时,Visual Studio 会显示建议吗?
  • 哪一行?如果是有问题的,它建议定义一个本地方法。如果你说的是 IntelliSense,它没有显示任何成员函数,只有 GetComponent 等函数(这很奇怪)
  • 您是否调用了您自己的MonoBehaviour 脚本AudioSource
  • @derHugo Asker 添加了链接包文件。他们可能是想通知你。
  • 我认为有。如何关闭问题?

标签: c# visual-studio unity3d


【解决方案1】:

我已经导入了你的包,看起来你有一个名为“AudioSource.cs”的脚本,它与 Unity 自己的 AudioSource 类冲突,在 deelaration 使用它:

  [SerializeField] UnityEngine.AudioSource audioSource;

会解决的

【讨论】:

    【解决方案2】:

    你只需添加头文件Using UnityEngine.Audio

    【讨论】:

      猜你喜欢
      • 2022-12-10
      • 1970-01-01
      • 1970-01-01
      • 2020-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-17
      • 1970-01-01
      相关资源
      最近更新 更多