Playing Audio via script in object, and adding audio lisener at runtime

I am playing around with Unity and experimenting a bit; I have this code that I am attempting to have to instantiate a cube with a sine.wav file. I want to avoid using the inspector if possible and have things instantiate in run time; here is the code I have; when I run it, everything seems to work as expected, except I don’t hear any audio.

public class Main : MonoBehaviour
{
    void Start()
    {
        // Spawn cube and add audio listener
        CubeSpawner spawner = gameObject.AddComponent<CubeSpawner>();
        spawner.SpawnCube(new Vector3(10, 10, 10), new Vector3(2, 2, 3));

        // Create a new game object and add an audio listener component to it
        GameObject audioListenerObj = new GameObject("Audio Listener");
        audioListenerObj.transform.position = Vector3.zero;
        audioListenerObj.AddComponent<AudioListener>();
    }
}

public class CubeSpawner : MonoBehaviour
{
    public GameObject cubePrefab;  // the prefab for the cube we want to spawn

    public void SpawnCube(Vector3 position, Vector3 size)
    {
        GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube); // create a cube object
        cube.transform.position = position; // set the position of the cube to the specified position
        cube.transform.localScale = size; // set the scale of the cube to the specified size
        cube.AddComponent<Cube>(); // add the Cube script to the cube object
        
        // add Rigidbody component to the cube
        Rigidbody rb = cube.AddComponent<Rigidbody>();
        rb.mass = 1;
        rb.useGravity = true;

        // add MeshCollider component to the cube
        MeshCollider meshCollider = cube.AddComponent<MeshCollider>();
        meshCollider.convex = true;
    }
}

[RequireComponent(typeof(AudioSource))]
public class Cube : MonoBehaviour
{
    public float amplitude = 0.5f; // amplitude of the sine wave
    public float frequency = 440f; // frequency of the sine wave
    public float speed = 1f; // speed of the sine wave

    private Vector3 startPosition; // starting position of the cube
    private AudioSource audioSource; // audio source component attached to the cube

    void Start()
    {
        startPosition = transform.position; // store the starting position of the cube
        audioSource = GetComponent<AudioSource>(); // get the audio source component attached to the cube
        audioSource.loop = true; // enable looping for the audio source
    }

    void Update()
    {
        // calculate the sine wave value based on time
        float time = Time.time * speed;
        float sineValue = amplitude * Mathf.Sin(2 * Mathf.PI * frequency * time);

        // apply the sine wave to the Y position of the cube
        transform.position = startPosition + new Vector3(0f, sineValue, 0f);

        // set the audio source pitch to the sine wave value
        float pitch = Mathf.InverseLerp(-1f, 1f, sineValue);
        audioSource.pitch = Mathf.Lerp(0.5f, 2f, pitch);

        // play the audio source
        if (!audioSource.isPlaying) {
            audioSource.Play();
        }
    }
}

Any idea about what I am doing wrong? Thanks for any feedback.

@nill_milk - I think you’re missing the AudioClip assignment for the AudioSource component. You should load the sine.wav file and assign it to the AudioSource component’s AudioClip property. You can load the AudioClip using Resources.Load() if you put the sine.wav file in a “Resources” folder in your Assets directory.

Try this:

[RequireComponent(typeof(AudioSource))]
public class Cube : MonoBehaviour
{
    public float amplitude = 0.5f;
    public float frequency = 440f;
    public float speed = 1f;

    private Vector3 startPosition;
    private AudioSource audioSource;

    void Start()
    {
        startPosition = transform.position;
        audioSource = GetComponent<AudioSource>();
        audioSource.loop = true;

        // Load the AudioClip and assign it to the AudioSource
        AudioClip clip = Resources.Load<AudioClip>("sine");
        audioSource.clip = clip;
    }

    void Update()
    {
        float time = Time.time * speed;
        float sineValue = amplitude * Mathf.Sin(2 * Mathf.PI * frequency * time);

        transform.position = startPosition + new Vector3(0f, sineValue, 0f);

        float pitch = Mathf.InverseLerp(-1f, 1f, sineValue);
        audioSource.pitch = Mathf.Lerp(0.5f, 2f, pitch);

        if (!audioSource.isPlaying) {
            audioSource.Play();
        }
    }
}

Make sure to put your sine.wav file in a folder named “Resources” in your Assets directory. The AudioClip will be loaded from the Resources folder using the file name without the extension (in this case, just “sine”).

Let me know if that helps…