Skip to content

Extra: Setting up AudioScript

Emik edited this page Aug 31, 2021 · 1 revision

Explanation

AudioScript is a component which encapsulates an AudioSource and automatically scales the volume according to the game's volume. Being a built-in Unity component, AudioSource has many useful parameters and methods over KMAudio and is primarily good for playing music, longer sounds, or generally implement automation into your sounds.

For more information about each method that AudioScript has, refer to the exhaustive documentation's AudioScript page.

Despite this library being strongly named which would normally allow multiple different versions of this library to be loaded, Unity is unable to distinguish the libraries from each other with components declared in this library if "Parallel Mod Loading" is enabled. As such, KeepCoding 10+ has changed AudioScript to be abstract which no longer allows you to attach it to your scripts directly.


Declaration

Declare your own class that inherits from this class. This allows the game to correctly point to the version of the library you are using, and resolve the conflict. Use this newly-defined component to attach to your class.

using KeepCoding;

public sealed class AudioPatcher : AudioScript { }

You may still use Get<AudioScript> or Get<AudioPatcher> to refer to your own audio sources, there is no difference.

You may also define your own logic in here if needed. Make sure not to override Awake or Update without calling their base methods, or use OnAwake and OnUpdate instead.

using KeepCoding;
using UnityEngine;

public sealed class AudioPatcher : AudioScript
{
    public override void OnAwake()
    {
        AudioSource.pitch = 1.5f;
    }

    protected void Update()
    {
        base.Update();
        AudioSource.time = Random.Range(0, 10f);
    }
}
Clone this wiki locally