📜  audioSource unity - C# (1)

📅  最后修改于: 2023-12-03 15:13:33.212000             🧑  作者: Mango

AudioSource Unity - C#

Introduction:

AudioSource is a component of Unity's Audio API that allows developers to play sounds from a game object. With its various properties and methods, it enables developers to manipulate sound in various ways, such as volume, pitch, stereo panning, 3D spatialization, looping, and more.

Properties:

The following are some of the essential properties of the AudioSource component:

clip

The AudioClip to be played by the AudioSource.

volume

The volume of the sound, ranging from 0.0 to 1.0.

pitch

The pitch of the sound, ranging from 0.1 to 3.0.

panStereo

The stereo pan of the sound, ranging from -1.0 (fully left) to 1.0 (fully right).

spatialBlend

The 3D spatial blend of the sound, ranging from 0.0 (2D) to 1.0 (3D).

loop

A boolean value indicating whether the sound should loop.

playOnAwake

A boolean value indicating whether the sound should start playing automatically on object instantiation.

priority

The priority of the sound, ranging from 0 to 256.

Methods:

The following are some of the essential methods of the AudioSource component:

Play()

Plays the attached AudioClip.

Pause()

Pauses the currently playing AudioClip.

Stop()

Stops playing the currently playing AudioClip.

Code Snippet:

The following is an example of how to use AudioSource:

public class AudioManager : MonoBehaviour
{
    public static AudioManager instance;

    public AudioSource audioSource;

    private void Awake()
    {
        if (instance == null)
        {
            instance = this;
        }
        else
        {
            Destroy(gameObject);
        }
    }

    public void PlaySound(AudioClip clip, float volume)
    {
        audioSource.clip = clip;
        audioSource.volume = volume;
        audioSource.Play();
    }

    public void StopSound()
    {
        audioSource.Stop();
    }
}

In this code snippet, we create a singleton AudioManager script that contains an AudioSource component. We also create two public methods, PlaySound() and StopSound(), that allow us to start and stop playing a sound respectively. We make use of the audioSource variable to set the clip and volume of the sound, and then play it using the Play() method.