Search code examples
c#unity-game-enginevuforia

Play audio when model renders in Vuforia for Unity3D


I am trying to play a sound clip when an object is rendered in Vuforia. I found a solution in Vuforia forums for this but is not working for me, in fact Unity crahes.

The solutions consist in altering the file \Assets\Vuforia\Scripts\DefaultTrackableEventHandler.cs from Vuforia's source code:

private void OnTrackingFound()
{
    Renderer[] rendererComponents = GetComponentsInChildren<Renderer>(true);
    Collider[] colliderComponents = GetComponentsInChildren<Collider>(true);

    // *** Additional Audio code 
    foreach (Transform child in transform)
    {
        child.audio.Play();
    }

    // Enable rendering:
    foreach (Renderer component in rendererComponents)
    {
        component.enabled = true;
    }

    // Enable colliders:
    foreach (Collider component in colliderComponents)
    {
        component.enabled = true;
    }

    Debug.Log("Trackable " + mTrackableBehaviour.TrackableName + " found");
}


private void OnTrackingLost()
{
    Renderer[] rendererComponents = GetComponentsInChildren<Renderer>(true);
    Collider[] colliderComponents = GetComponentsInChildren<Collider>(true);

    // *** Additional Audio code
    foreach (Transform child in transform)
    {
        child.audio.Stop();
    }

    // Disable rendering:
    foreach (Renderer component in rendererComponents)
    {
        component.enabled = false;
    }

    // Disable colliders:
    foreach (Collider component in colliderComponents)
    {
        component.enabled = false;
    }

    Debug.Log("Trackable " + mTrackableBehaviour.TrackableName + " lost");
}

It just adds child.audio.Play(); to be called on OnTrackingFound() and child.audio.Stop(); to be called on OnTrackingLost()

This should work in theory, I added the audio file as a child for the Image Target, but because 'Component.audio' has been deprecated I had to change it to GetComponent<AudioSource>() instead. So the code ended like this:

    // *** Additional Audio code
    foreach (Transform child in transform)
    {
        child.GetComponent<AudioSource>().Play();
    }

And

    // *** Additional Audio code
    foreach (Transform child in transform)
    {
        child.GetComponent<AudioSource>().Stop();
    }

Why is it not working?

Did I used GetComponent<AudioSource>() wrong?

Is there an alternative?


Solution

  • There is a very simple alternative to this. Add the audiosource to the object and make sure play on awake and loop is checked.

    And on tracking found set your gameobject active true, on tracking lost set it to false.