Home > front end >  'AudioSource' does not contain a definition for 'PlayOneShot' in Unity
'AudioSource' does not contain a definition for 'PlayOneShot' in Unity

Time:11-23

I have created in a Unity project a GameObject with a AudioSource component. I believe I have appropriately used the GetComponent function properly to access the said component. I am trying to use the PlayOneShot() function through the script, but it does not compile. I'm using Unity 2020.3.22f1 (LTS) and Visual Studio for Mac 8.10.14.

Link to Unity Package file: https://1drv.ms/u/s!AvhOYSsJUBS1hUocvPEgfmkwHfeh

Script:

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;
        }
    }
}

CodePudding user response:

I have imported your package and it seems like you have a script named as "AudioSource.cs" which is conflicting with Unity's own AudioSource class use this at decelaration :

  [SerializeField] UnityEngine.AudioSource audioSource;

And it will be solved

CodePudding user response:

You just can add the header file Using UnityEngine.Audio

  • Related