# Stop an instance in Unity

**URL:** <https://qa.fmod.com/t/stop-an-instance-in-unity/22010>\
**Category:** Unity\
**Created:** [August 16, 2024, 6:27pm UTC](https://qa.fmod.com/t/stop-an-instance-in-unity/22010 "2024-08-16T18:27:03Z")\
**Posts on this page:** 10\
**Page:** 1

<div class="post-metadata">

**Author:** ![AntvilStudios](https://avatars.discourse-cdn.com/v4/letter/a/7feea3/32.png) [@AntvilStudios](https://qa.fmod.com/u/AntvilStudios)\
**Post date:** [August 16, 2024, 6:27pm UTC](https://qa.fmod.com/t/stop-an-instance-in-unity/22010/1 "2024-08-16T18:27:03Z")

</div>

Hello, excuse me if it´s a very noobie question but i´m learning to code.

I have a Game menu wich i want some music to be played, but when the player presses Play button i want the music to be stopped. Thing is i´ve managed to start the sound but i can´t figure out how to stop it. Any help will be appreciated.

This is the code:

```auto
 private void Start()
    {
        Overmind.Instance.LanguageChanged += RefreshLanguage;  
        RefreshLanguage(Overmind.Instance.Language);
var MM = RuntimeManager.CreateInstance("event:/Menú Principal");
MM.start();
MM.release();
    }
    public void Click_Play()
    {
        Overmind.Instance.SoundManager.UIClick();
        Game.NewGame(ECheckpoint.None);
        gameObject.SetActive(false);

    }

```

---

<div class="post-metadata">

**Author:** ![Connor\_FMOD](https://yyz2.discourse-cdn.com/flex036/user_avatar/qa.fmod.com/connor_fmod/32/3685_2.png) [@Connor\_FMOD](https://qa.fmod.com/u/Connor_FMOD)\
**Post date:** [August 19, 2024, 2:08am UTC](https://qa.fmod.com/t/stop-an-instance-in-unity/22010/2 "2024-08-19T02:08:01Z")

</div>

Hi, no worries!

What we will want to do is keep a reference to the [Event Instance](https://fmod.com/docs/2.02/api/studio-api-eventinstance.html) rather than just in the `Start()` function.  
Create a

```auto
private FMOD.Studio.EventInstance MM; 

```

variable.  
Then we will be able to assign the instance to it from `RuntimeManager.CreateInstance` while also being able to call in from the `public void Click_Play()` function.

To aid with debugging I would also suggest learning about our [FMOD\_RESULT](https://fmod.com/docs/2.02/api/core-api-common.html#fmod_result) which is returned from most of our functions. You can check the result using something like this:

```auto
FMOD.RESULT result = MM.start();
if (result != FMOD.OK)
{
    Debug.Log(result);
}

```

Hope this helps! If you have any more questions, please do not hesitate to ask.

---

<div class="post-metadata">

**Author:** ![AntvilStudios](https://avatars.discourse-cdn.com/v4/letter/a/7feea3/32.png) [@AntvilStudios](https://qa.fmod.com/u/AntvilStudios)\
**Post date:** [August 22, 2024, 12:42pm UTC](https://qa.fmod.com/t/stop-an-instance-in-unity/22010/3 "2024-08-22T12:42:05Z")

</div>

Thank you for your reply!.

Unfortunately it´s not working and Unity returns some errors. The code has been re-worked but still returns errors. The idea is playing menu music when players go the menu and, when they return to the area he´s located, the menu music stops and plays again the music of the area they are located, which leads me to another questions:  
Which command should i use regarding labeled parameters?  
Which code should i use to get variables from C# code in Unity to my FMOD events?  
This would be the new code to implement the instance:

```auto
    public void MenuMusic(bool shouldPlay)
    {
        switch (currentMusic)
        {
            case EMusic.Sand:
                if (shouldPlay)
                {
                    //stop area music
                    var MM = RuntimeManager.CreateInstance("event:/EL TERROR ERRANTE/Música/Menús/Menú_Pral");
                    FMOD.RESULT result = MM.start();
                }
                else
                {
                RuntimeManager.PlayOneShot("event:/EL TERROR ERRANTE/Ambientes/Naturaleza/Desierto");
                
               //play area music   
                }       
                break;

            case EMusic.Forest:
                if (shouldPlay)
                {
                    //stop area Music
                }
                else
                {
                    //play area music
                }
                break;

            case EMusic.BossApproach:
                if (shouldPlay)
                {
                    //stop area Music
                }
                else
                {
                    //play area music
                }
                break;

            case EMusic.Boss:
                if (shouldPlay)
                {
                    //stop area Music
                }
                else
                {
                    //play area music
                }
                break;
        }

        if (shouldPlay)
        {
            //play menu music
        } else
        {
            //stop menu music
        }
    }

```

Thank you in advance  
Best Regards

---

<div class="post-metadata">

**Author:** ![Connor\_FMOD](https://yyz2.discourse-cdn.com/flex036/user_avatar/qa.fmod.com/connor_fmod/32/3685_2.png) [@Connor\_FMOD](https://qa.fmod.com/u/Connor_FMOD)\
**Post date:** [August 23, 2024, 12:03am UTC](https://qa.fmod.com/t/stop-an-instance-in-unity/22010/4 "2024-08-23T00:03:52Z")

</div>

No worries!

> [@AntvilStudios](#):
>
> Unfortunately it´s not working and Unity returns some errors. The code has been re-worked but still returns errors

Would it be possible to share those error codes?

> [@AntvilStudios](#):
>
> Which command should i use regarding labeled parameters?

To set a labeled parameter you’d call [Studio::EventInstance::setParameterByNameWithLabel](https://fmod.com/docs/2.02/api/studio-api-eventinstance.html#studio_eventinstance_setparameterbynamewithlabel).

> [@AntvilStudios](#):
>
> Which code should i use to get variables from C# code in Unity to my FMOD events?

I am unsure what you mean by this, could you give me an example? You may be looking for [EventInstance::setParameterByName](https://fmod.com/docs/2.02/api/studio-api-eventinstance.html#studio_eventinstance_setparameterbyname).

Thank you for the code example. The issue is possibly using a local parameter for your event instance. For example:

```auto
if (shouldPlay)
{
	//stop area music
	var MM = RuntimeManager.CreateInstance("event:/EL TERROR ERRANTE/Música/Menús/Menú_Pral");
	FMOD.RESULT result = MM.start();
}

```

here, once you leave the if statement you lose reference to `MM` making it difficult to stop again. I would suggest making a [member variable](https://docs.unity3d.com/Manual/VariablesAndTheInspector.html) for the event instance so you can reference it from anywhere in the `MenuMusic` function. Also, here you are correctly collecting the result of `MM.start()` but I would suggest checking the result with something like:

```auto
if (result != FMOD.OK)
{
   Debug.Log(result);
}

```

Then you will get a console log with the error.

Hope this helps!

---

<div class="post-metadata">

**Author:** ![AntvilStudios](https://avatars.discourse-cdn.com/v4/letter/a/7feea3/32.png) [@AntvilStudios](https://qa.fmod.com/u/AntvilStudios)\
**Post date:** [August 26, 2024, 6:16pm UTC](https://qa.fmod.com/t/stop-an-instance-in-unity/22010/5 "2024-08-26T18:16:22Z")

</div>

Hi, sorry for the late response.

> Blockquote  
> I have an event (a music box sound) which has 3 parameters:

- Distance
- Cone Angle
- Elevation

First two i am managing to obtain the values, although the third i am getting unreasonable values (the object is in the same horizontal plane as the main camera, and still getting negative values).  
This is important because depending on the values, the event will play differently or not play at all.

I am using SetParameterByName to set the values, but the events are not working. In this point i don´t know if the emitters are not working or the code is plain wrong.

This is the code for calculating parameters:

```auto
 //CALCULAR EL ÁNGULO CÓNICO BOSS
    public float CalculateConeAngle(GameObject emitter)
    {
        // Buscar la cámara por nombre
        Camera mainCamera = GameObject.Find("Camera").GetComponent<Camera>();

        // Verificar si la cámara fue encontrada
        if (mainCamera == null)
        {
            Debug.LogError("No se encontró la cámara con el nombre 'Camera' en la escena.");
            return 0f; // Retornar un valor por defecto
        }

        Vector3 listenerPosition = mainCamera.transform.position;

        // Dirección del emisor
        Vector3 emitterForward = emitter.transform.forward;

        // Dirección desde el emisor hacia el oyente (cámara principal)
        Vector3 directionToListener = (listenerPosition - emitter.transform.position).normalized;

        // Calcular el ángulo entre la dirección del emisor y la dirección hacia el oyente
        float angle = Vector3.Angle(emitterForward, directionToListener);

        return angle;
    }

    //CALUCULAR DISTANCIA
    public float CalculateDistance(GameObject emitter)
    {
        // Buscar la cámara por nombre
        Camera mainCamera = GameObject.Find("Camera").GetComponent<Camera>();

        // Verificar si la cámara fue encontrada
        if (mainCamera == null)
        {
            Debug.LogError("No se encontró la cámara con el nombre 'Camera' en la escena.");
            return 0f; // Retornar un valor por defecto
        }

        // Calcular la distancia entre el emisor y el oyente
        float distance = Vector3.Distance(emitter.transform.position, mainCamera.transform.position);

        return distance;
    }
    //CALCULAR ELEVACIÓN
    float CalculateElevation(GameObject emitter)
    {
        //GameObject emitter = GameObject.FindWithTag("Caja de Musica");
        // Obtener la cámara principal como oyente
        Camera mainCamera = GameObject.Find("Camera").GetComponent<Camera>();
        // Posiciones del oyente y del emisor
        Vector3 listenerPosition = mainCamera.transform.position;
        Vector3 emitterPosition = emitter.transform.position;

        // Vector dirección desde el oyente hacia el emisor
        Vector3 direction = emitterPosition - listenerPosition;

        // Obtener la distancia horizontal (en el plano XZ) y la diferencia de altura
        float horizontalDistance = Mathf.Sqrt(direction.x * direction.x + direction.z * direction.z);
        float verticalDistance = direction.y;

        // Calcular el ángulo de elevación usando arctan2
        float elevationAngle = Mathf.Atan2(verticalDistance, horizontalDistance) * Mathf.Rad2Deg;

        return elevationAngle;
    }

```

And this is the code to update the values

```auto
 public void Update()
    {
        // Actualizar los atributos 3D en cada frame para cada emisor
        Set3DAttributes(emitter1, musicBox);
        Set3DAttributes(emitter2, bossApproachMusic);

        // Calcular y establecer parámetros para el primer emisor
        float coneAngle1 = CalculateConeAngle(emitter1);
        float distance1 = CalculateDistance(emitter1);
        float elevationAngle = CalculateElevation(emitter1);
        musicBox.setParameterByName("ConeAngle", coneAngle1);
        musicBox.setParameterByName("Distance", distance1);
        musicBox.setParameterByName("Music Box Floor", elevationAngle);
        Debug.Log($"Elevación de la caja de música (emitter1) es: {elevationAngle}");
        // Calcular y establecer parámetros para el segundo emisor
        float coneAngle2 = CalculateConeAngle(emitter2);
        float distance2 = CalculateDistance(emitter2);
        bossApproachMusic.setParameterByName("ConeAngle", coneAngle2);
        bossApproachMusic.setParameterByName("Distance", distance2);
        Debug.Log($"Distancia desde la caja de música al oyente: {distance1}");
        Debug.Log($"Distancia desde el boss al oyente: {distance2}");
    }

```

And finally the start ()

```auto
 private void Start()
    {
        UpdateSoundSettings();
        dialogueCallback = new EVENT_CALLBACK(DialogueEventCallback);
        //Set3DAttributes();
                // Configurar los atributos 3D al inicio para cada emisor
        Set3DAttributes(emitter1, musicBox);
        Set3DAttributes(emitter2, bossApproachMusic);

        // Iniciar la reproducción del evento para cada emisor
        MusicBox.start();
        bossApproachMusic.start();

    }

```

I´ve placed the emitters in the gameObjects and i don´t know what i am doing wrong.

Thank you in advance.

---

<div class="post-metadata">

**Author:** ![Connor\_FMOD](https://yyz2.discourse-cdn.com/flex036/user_avatar/qa.fmod.com/connor_fmod/32/3685_2.png) [@Connor\_FMOD](https://qa.fmod.com/u/Connor_FMOD)\
**Post date:** [August 27, 2024, 4:47am UTC](https://qa.fmod.com/t/stop-an-instance-in-unity/22010/6 "2024-08-27T04:47:24Z")

</div>

Thank you for the code.

> [@AntvilStudios](#):
>
> - Distance
> - Cone Angle
> - Elevation

We supply built-in parameters that can calculate these values for you within FMOD Studio: [FMOD Studio | Parameter Reference - Built-in Parameters](https://fmod.com/docs/2.02/studio/parameters-reference.html#built-in-parameters). It will only require the emitter object to have a rigid body. Let me know if you have any issues using these.

Could you please add some `FMOD.RESULT` logs to the`setParameterByName` calls so that we can see if they are returning any errors?

What is happening in this function `Set3DAttributes()`?

How are you setting the `MusicBox` and the `bossApproachMusic` variables? Would it be possible to share the whole class?

What version of the FMOD integration are you using?  
 ![image](https://canada1.discourse-cdn.com/flex036/uploads/fmod/original/2X/1/1cb41ba5cc6da27c470b49fd950760b0ac838d48.png)  
 ![image](https://canada1.discourse-cdn.com/flex036/uploads/fmod/original/2X/7/7681f25f21a4fd2496fdcdd9b4e7b115f0ca9fbe.png)

---

<div class="post-metadata">

**Author:** ![AntvilStudios](https://avatars.discourse-cdn.com/v4/letter/a/7feea3/32.png) [@AntvilStudios](https://qa.fmod.com/u/AntvilStudios)\
**Post date:** [August 27, 2024, 8:40am UTC](https://qa.fmod.com/t/stop-an-instance-in-unity/22010/7 "2024-08-27T08:40:59Z")

</div>

> [@Connor\_FMOD](#):
>
> We supply built-in parameters that can calculate these values for you within FMOD Studio: [FMOD Studio | Parameter Reference - Built-in Parameters](https://fmod.com/docs/2.02/studio/parameters-reference.html#built-in-parameters). It will only require the emitter object to have a rigid body. Let me know if you have any issues using these.

Sorry for the question: How can I do that ? . I mean, i did the FMOD event with Built - in parameters as you can see in the screenshot, but they don´t seem to work with Unity. They work perfectly in FMOD although. And yes, both gameObjects have a rigibody.

 ![event_mbox](https://canada1.discourse-cdn.com/flex036/uploads/fmod/original/2X/3/3898fa98f1b41d8e5f48512f22677f3adab9e4d3.png)  
Inspector MBox  
 ![inspector_mbox](https://canada1.discourse-cdn.com/flex036/uploads/fmod/original/2X/2/23c5185b9bc955137b2d4f1d43e0b87f24413d18.png)  
Inspector Boss  
 ![inspector_boss](https://canada1.discourse-cdn.com/flex036/uploads/fmod/original/2X/0/00b0136910f503c9077e3a23cb2c20d78b7f6c9e.png)

> [@Connor\_FMOD](#):
>
> Could you please add some `FMOD.RESULT` logs to the`setParameterByName` calls so that we can see if they are returning any errors?

I don´t know how to do that, I´m starting in this world of coding 🥴

> [@Connor\_FMOD](#):
>
> What is happening in this function `Set3DAttributes()`?

This:

```auto
public void Set3DAttributes(GameObject emitter, FMOD.Studio.EventInstance eventInstance)
    {
        // Obtener la posición y la orientación del objeto
        Vector3 position = transform.position;
        Vector3 forward = transform.forward;
        Vector3 up = transform.up;

        // Crear la estructura de atributos 3D de FMOD
        FMOD.ATTRIBUTES_3D attributes = new FMOD.ATTRIBUTES_3D();
        attributes.position = FMODUnity.RuntimeUtils.ToFMODVector(position);
        attributes.forward = FMODUnity.RuntimeUtils.ToFMODVector(forward);
        attributes.up = FMODUnity.RuntimeUtils.ToFMODVector(up);

        // Opcional: también puedes configurar la velocidad si es relevante para el doppler
        attributes.velocity = FMODUnity.RuntimeUtils.ToFMODVector(Vector3.zero);

        // Establecer los atributos 3D en la instancia del evento DesertAmbience
        DesertAmbience.set3DAttributes(attributes);
        BosqueAmbience.set3DAttributes(attributes);
        bossApproachMusic.set3DAttributes(attributes);
        bossMusic.set3DAttributes(attributes);
        eventInstance.set3DAttributes(attributes); 
        }

```

> [@Connor\_FMOD](#):
>
> How are you setting the `MusicBox` and the `bossApproachMusic` variables? Would it be possible to share the whole class?

Certainly. Here is the code:

```auto
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using FMODUnity;
using FMOD.Studio;
using System.Runtime.InteropServices;

public class SoundManager : MonoBehaviour
{
    public static SoundManager Instance { get; private set; }

    EVENT_CALLBACK dialogueCallback;

    private EventInstance musicBox;
    private EventInstance bossApproachMusic;
    //private EventInstance BossApproachMus;
    private bool menuMusicInitialized;
    //private EventInstance RecogerGema;
    //private EventInstance RecogerCaja;
    private List<EventInstance> eventInstances;
    private List<StudioEventEmitter> eventEmitters;
    public GameObject emitter1; // Asigna en el Inspector o busca por nombre
    public GameObject emitter2; // Asigna en el Inspector o busca por nombre

    public void Awake()
    {
        Instance = this;
        eventInstances = new List<EventInstance>();
        eventEmitters = new List<StudioEventEmitter>();
        bossApproachMusic = CreateInstance(FMODEvents.Instance.BossApproachMus);
        musicBox = CreateInstance(FMODEvents.Instance.CajaMusica);
        //RecogerGema = CreateInstance(FMODEvents.Instance.Recoger);
        //RecogerCaja = CreateInstance(FMODEvents.Instance.Recoger);

    }

    private void Start()
    {

        UpdateSoundSettings();
        dialogueCallback = new EVENT_CALLBACK(DialogueEventCallback);
        //Set3DAttributes();
        // Configurar los atributos 3D al inicio para cada emisor
        Set3DAttributes(emitter1, musicBox);
        Set3DAttributes(emitter2, bossApproachMusic);

        // Iniciar la reproducción del evento para cada emisor
        musicBox.start();
        FMOD.RESULT MBoxresult = musicBox.start();
        if (MBoxresult != FMOD.RESULT.OK)
        {
            Debug.Log(MBoxresult);
        }
        bossApproachMusic.start();
        FMOD.RESULT bAMresult = bossApproachMusic.start();
        if (bAMresult != FMOD.RESULT.OK)
        {
            Debug.Log(bAMresult);
        }
    }
    public void Update()
    {
        // Actualizar los atributos 3D en cada frame para cada emisor
        Set3DAttributes(emitter1, musicBox);
        Set3DAttributes(emitter2, bossApproachMusic);

        // Calcular y establecer parámetros para el primer emisor
        float coneAngle1 = CalculateConeAngle(emitter1);
        float distance1 = CalculateDistance(emitter1);
        float elevationAngle = CalculateElevation(emitter1);
        musicBox.setParameterByName("ConeAngle", coneAngle1);
        musicBox.setParameterByName("Distance", distance1);
        musicBox.setParameterByName("Music Box Floor", elevationAngle);
        Debug.Log($"Music Box Elevation (emitter1) is: {elevationAngle}");
        // Calcular y establecer parámetros para el segundo emisor
        float coneAngle2 = CalculateConeAngle(emitter2);
        float distance2 = CalculateDistance(emitter2);
        bossApproachMusic.setParameterByName("ConeAngle", coneAngle2);
        bossApproachMusic.setParameterByName("Distance", distance2);
        Debug.Log($"Music Box distance is : {distance1}");
        Debug.Log($"Boss distance is : {distance2}");
        Debug.Log($"Music Box angle is : {coneAngle1}");
        Debug.Log($"Boss angle is : {coneAngle2}");
    }
    public void CajadeMusica()
    {
        // Calcular y establecer parámetros para el primer emisor
        float elevationAngle = CalculateElevation(emitter1);
        float coneAngle1 = CalculateConeAngle(emitter1);
        float distance1 = CalculateDistance(emitter1);
        musicBox.setParameterByName("ConeAngle", coneAngle1);
        musicBox.setParameterByName("Distance", distance1);
        musicBox.setParameterByName("Music Box Floor", elevationAngle);
    }
    public void BossApproach()
    {

        Set3DAttributes(emitter2, bossApproachMusic);
        // Calcular y establecer parámetros 
        float coneAngle2 = CalculateConeAngle(emitter2);
        float distance2 = CalculateDistance(emitter2);
        bossApproachMusic.setParameterByName("Angle", coneAngle2);
        bossApproachMusic.setParameterByName("Distance", distance2);
        if (distance2 <= 50)
        {
            bossApproachMusic.setParameterByName("Initiated", 0);
            bossApproachMusic.setParameterByName("Distance", distance2);
            bossApproachMusic.setParameterByName("Angle", coneAngle2);
            bossApproachMusic.start();
            FMOD.RESULT baM = bossApproachMusic.start();
            if (baM != FMOD.RESULT.OK)
            {
                Debug.Log(baM);
            }
        }
        else
        {
            bossApproachMusic.stop(FMOD.Studio.STOP_MODE.ALLOWFADEOUT);
        }

    }

    //FMOD.Studio.EVENT_CALLBACK dialogueCallback;
    //crea instancias    
    public EventInstance CreateInstance(EventReference eventReference)
    {
        EventInstance eventInstance = RuntimeManager.CreateInstance(eventReference);
        eventInstances.Add(eventInstance);
        return eventInstance;
    }
    //ATRIBUTOS 3D AMBIENTES
    public void Set3DAttributes(GameObject emitter, FMOD.Studio.EventInstance eventInstance)
    {
        // Obtener la posición y la orientación del objeto
        Vector3 position = transform.position;
        Vector3 forward = transform.forward;
        Vector3 up = transform.up;

        // Crear la estructura de atributos 3D de FMOD
        FMOD.ATTRIBUTES_3D attributes = new FMOD.ATTRIBUTES_3D();
        attributes.position = FMODUnity.RuntimeUtils.ToFMODVector(position);
        attributes.forward = FMODUnity.RuntimeUtils.ToFMODVector(forward);
        attributes.up = FMODUnity.RuntimeUtils.ToFMODVector(up);

        // Opcional: también puedes configurar la velocidad si es relevante para el doppler
        attributes.velocity = FMODUnity.RuntimeUtils.ToFMODVector(Vector3.zero);

        // Establecer los atributos 3D en la instancia del evento DesertAmbience
        bossApproachMusic.set3DAttributes(attributes);
        musicBox.set3DAttributes(attributes);
        bossMusic.set3DAttributes(attributes);
        eventInstance.set3DAttributes(attributes);
    }
    //CALCULAR EL ÁNGULO CÓNICO BOSS
    public float CalculateConeAngle(GameObject emitter)
    {
        // Buscar la cámara por nombre
        Camera mainCamera = GameObject.Find("Camera").GetComponent<Camera>();

        // Verificar si la cámara fue encontrada
        if (mainCamera == null)
        {
            Debug.LogError("No se encontró la cámara con el nombre 'Camera' en la escena.");
            return 0f; // Retornar un valor por defecto
        }

        Vector3 listenerPosition = mainCamera.transform.position;

        // Dirección del emisor
        Vector3 emitterForward = emitter.transform.forward;

        // Dirección desde el emisor hacia el oyente (cámara principal)
        Vector3 directionToListener = (listenerPosition - emitter.transform.position).normalized;

        // Calcular el ángulo entre la dirección del emisor y la dirección hacia el oyente
        float angle = Vector3.Angle(emitterForward, directionToListener);

        return angle;
    }

    //CALUCULAR DISTANCIA
    public float CalculateDistance(GameObject emitter)
    {
        // Buscar la cámara por nombre
        Camera mainCamera = GameObject.Find("Camera").GetComponent<Camera>();

        // Verificar si la cámara fue encontrada
        if (mainCamera == null)
        {
            Debug.LogError("No se encontró la cámara con el nombre 'Camera' en la escena.");
            return 0f; // Retornar un valor por defecto
        }

        // Calcular la distancia entre el emisor y el oyente
        float distance = Vector3.Distance(emitter.transform.position, mainCamera.transform.position);

        return distance;
    }
    //CALCULAR ELEVACIÓN
    float CalculateElevation(GameObject emitter)
    {
        //GameObject emitter = GameObject.FindWithTag("Caja de Musica");
        // Obtener la cámara principal como oyente
        Camera mainCamera = GameObject.Find("Camera").GetComponent<Camera>();
        // Posiciones del oyente y del emisor
        Vector3 listenerPosition = mainCamera.transform.position;
        Vector3 emitterPosition = emitter.transform.position;

        // Vector dirección desde el oyente hacia el emisor
        Vector3 direction = emitterPosition - listenerPosition;

        // Obtener la distancia horizontal (en el plano XZ) y la diferencia de altura
        float horizontalDistance = Mathf.Sqrt(direction.x * direction.x + direction.z * direction.z);
        float verticalDistance = direction.y;

        // Calcular el ángulo de elevación usando arctan2
        float elevationAngle = Mathf.Atan2(verticalDistance, horizontalDistance) * Mathf.Rad2Deg;

        return elevationAngle;
    }
    //INICIAR EVENT EMITTERS
    public StudioEventEmitter InitalizeEventEmitter(EventReference eventReference, GameObject emitterGameObject)
    {
        StudioEventEmitter emitter = emitterGameObject.GetComponent<StudioEventEmitter>();
        emitter.EventReference = eventReference;
        eventEmitters.Add(emitter);
        return emitter;
    }

    //ONESHOTS
    public void PlayOneShot(EventReference sound, Vector3 worldPos)
    {
        RuntimeManager.PlayOneShot(sound, worldPos);
    }

    public enum EMusic
    {
        Menu,
        Sand,
        Forest,
        BossApproach,
        MusicBox
        Boss
    }
    private EMusic currentMusic;

    public void MenuMusic(bool shouldPlay)
    {
        switch (currentMusic)
        {
            case EMusic.Sand:
                if (shouldPlay)
                {
                    //stop area music
                    sandMusic.setPaused(true);
                }
                else
                {
                    //play area music   
                    sandMusic.setPaused(false);

                }
                break;

            case EMusic.Forest:
                if (shouldPlay)
                {
                    //stop area Music
                    forestMusic.setPaused(true);
                }
                else
                {
                    //play area music
                    forestMusic.setPaused(true);
                }
                break;

            case EMusic.BossApproach:
                if (shouldPlay)
                {
                    //stop area Music
                    bossApproachMusic.setPaused(true);
                }
                else
                {
                    //play area music
                    bossApproachMusic.setPaused(true);
                }
                break;

            case EMusic.Boss:
                if (shouldPlay)
                {
                    //stop area Music
                    bossMusic.setPaused(true);
                }
                else
                {
                    //play area music
                    bossMusic.setPaused(true);
                }
                break;
        }

        if (shouldPlay)
        {
            //play menu music
            MenuMusica.start();
        }
        else
        {
            //stop menu music
            MenuMusica.stop(FMOD.Studio.STOP_MODE.ALLOWFADEOUT);
        }
    }

    public void PlayMusic(EMusic music)
    {
        switch (currentMusic)
        {
            case EMusic.Sand:
                //stop area music
                sandMusic.stop(FMOD.Studio.STOP_MODE.ALLOWFADEOUT);
                break;

            case EMusic.Forest:
                //stop area music
                forestMusic.stop(FMOD.Studio.STOP_MODE.ALLOWFADEOUT);
                break;
            case EMusic.MusicBox:
                //stop area music
                forestMusic.stop(FMOD.Studio.STOP_MODE.ALLOWFADEOUT);
                break;
            case EMusic.BossApproach:
                //stop area music
                bossApproachMusic.stop(FMOD.Studio.STOP_MODE.ALLOWFADEOUT);
                break;

            case EMusic.Boss:
                //stop area music
                bossApproachMusic.stop(FMOD.Studio.STOP_MODE.ALLOWFADEOUT);
                break;
        }

        currentMusic = music;
        switch (music)
        {
            case EMusic.Sand:
                //play area music
                sandMusic.start();
                DesertAmbience.start();
                break;

            case EMusic.Forest:
                //play area music
                forestMusic.start();
                DesertAmbience.stop(FMOD.Studio.STOP_MODE.ALLOWFADEOUT);
                Debug.Log("Se detiene el ambiente del desierto");
                BosqueAmbience.start();
                Debug.Log("Comienza el ambiente del bosque");
                break;
            case EMusic.MusicBox:
                //plays Music Box
                forestMusic.stop(FMOD.Studio.STOP_MODE.ALLOWFADEOUT);
                musicBox.start();
            case EMusic.BossApproach:
                //play area music
                bossApproachMusic.start();
                FMOD.RESULT bAMresult = bossApproachMusic.start();
                if (bAMresult != FMOD.RESULT.OK)
                {
                    Debug.Log(bAMresult);
                }
                Debug.Log("Empieza la música del Boss");
                BosqueAmbience.stop(FMOD.Studio.STOP_MODE.ALLOWFADEOUT);
                Debug.Log("Se detiene el ambiente del bosque");
                break;

            case EMusic.Boss:
                //play area music
                bossMusic.start();
                break;
        }

    }

    public void EnemyTalk(ETranslateID ID)
    {
        RuntimeManager.PlayOneShot("event:/EnemyTalk/" + ID.ToString());
        //RuntimeManager.PlayOneShot("event:/Dialog/BossTalkGreet");
    }

    public void UpdateSoundSettings()
    {
        areaMusicEventInstance.setVolume(Overmind.Instance.Config.Sounds.Music);
        MenuMusica.setVolume(Overmind.Instance.Config.Sounds.Music);
        sandMusic.setVolume(Overmind.Instance.Config.Sounds.Music);
        //value from 0->1
        //Overmind.Instance.Config.Sounds.General
        //Overmind.Instance.Config.Sounds.Ambients
        //Overmind.Instance.Config.Sounds.Dialogues
        //Overmind.Instance.Config.Sounds.SFX
        //Overmind.Instance.Config.Sounds.Music
    }

    public void PlayDialog(ETranslateID ID)
    {
        //RuntimeManager.PlayOneShot("event:/Dialog/" + ID.ToString());
        //RuntimeManager.PlayOneShot("event:/Dialog/dialog_0a");

        var dialogueInstance = RuntimeManager.CreateInstance(FMODEvents.Instance.Dialog);
        // Pin the key string in memory and pass a pointer through the user data
        GCHandle stringHandle = GCHandle.Alloc(ID.ToString());
        dialogueInstance.setUserData(GCHandle.ToIntPtr(stringHandle));

        dialogueInstance.setCallback(dialogueCallback);
        dialogueInstance.start();
        dialogueInstance.release();
    }

    private void Cleanup()
    {
        //Detiene las instancias creadas liberando memoria
        foreach (EventInstance eventInstance in eventInstances)
        {
            eventInstance.stop(FMOD.Studio.STOP_MODE.IMMEDIATE);
            eventInstance.release();
        }
        foreach (StudioEventEmitter emitter in eventEmitters)
        {
            emitter.Stop();
        }
    }
    private void OnDestroy()
    {
        Cleanup();
    }
}

```

> [@Connor\_FMOD](#):
>
> What version of the FMOD integration are you using?

This  
 ![version_FMOD](https://canada1.discourse-cdn.com/flex036/uploads/fmod/original/2X/7/7659b41c1b2fdef1feaa2ad9d3aa123eff16630a.png)

Thank you for all the support!

---

<div class="post-metadata">

**Author:** ![Connor\_FMOD](https://yyz2.discourse-cdn.com/flex036/user_avatar/qa.fmod.com/connor_fmod/32/3685_2.png) [@Connor\_FMOD](https://qa.fmod.com/u/Connor_FMOD)\
**Post date:** [August 28, 2024, 5:22am UTC](https://qa.fmod.com/t/stop-an-instance-in-unity/22010/8 "2024-08-28T05:22:37Z")

</div>

Thank you for the code and the images.

> [@AntvilStudios](#):
>
> Sorry for the question: How can I do that ?

No need to appoloies 🙂 The first thing we will want to fix up is choosing either to use the [Event Emitter](https://fmod.com/docs/2.02/unity/game-components.html#studio-event-emitter) or the [Event Reference](https://fmod.com/docs/2.02/unity/api-common.html#eventreference) you are calling in your script. Currently, you are playing the emitter while trying to access the event reference. These are two different things. I would suggest keeping the emitter and get a reference to its event instance with [StudioEventEmitter::EventInstance](https://fmod.com/docs/2.02/unity/api-studioeventemitter.html#studioeventemitter_eventinstance). This would look something like:

```auto
public class SoundManager : MonoBehaviour
{
	public static SoundManager Instance { get; private set; }

	EVENT_CALLBACK dialogueCallback;

	// ADD
	public StudioEventEmitter musicBoxEmitter;
	public StudioEventEmitter bossApproachEmitter;
    // REMOVE
	private EventInstance musicBox;
	private EventInstance bossApproachMusic;
//---------------------------------------

//CHANGE
public EventInstance CreateInstance(StudioEventEmitter emitter)
{
	eventInstances.Add(emitter.EventInstance);
	return emitter.EventInstance;
}

```

Now we are referencing the same instance as the emitter. Which should hopefully solve the setting and getting parameter issues. Let me know if this makes sense.

> [@AntvilStudios](#):
>
> I don´t know how to do that,

No worries, we talked about it already here: [Stop an instance in Unity - #2 by Connor\_FMOD](https://qa.fmod.com/t/stop-an-instance-in-unity/22010/2).

Thank you for the integration version. That version was released over 2 years ago, would it be possible to update to a more recent version?

We provide some scripting examples: [Unity Integration | Scripting Examples](https://fmod.com/docs/2.02/unity/examples.html), they may provide useful insights when working with the FMOD API.

Hope this helps!

---

<div class="post-metadata">

**Author:** ![AntvilStudios](https://avatars.discourse-cdn.com/v4/letter/a/7feea3/32.png) [@AntvilStudios](https://qa.fmod.com/u/AntvilStudios)\
**Post date:** [August 28, 2024, 1:57pm UTC](https://qa.fmod.com/t/stop-an-instance-in-unity/22010/9 "2024-08-28T13:57:40Z")

</div>

> [@Connor\_FMOD](#):
>
> ```auto
> public EventInstance CreateInstance(StudioEventEmitter emitter)
> {
> eventInstances.Add(emitter.EventInstance);
> return emitter.EventInstance;
> }
> 
> ```

Hi, the problem with replacing old code with that code is that all the instances independent of emitters stop playing.

Also what would be the correct syntax?

If i write this (EventInstance as _My instance_:  
**eventInstances.Add(musicBoxEmitter._My instance_)**  
return emitter._My instance_

It doesn´t work.

Also i´m getting another errors like:  
[FMOD] Instance of Event event:/EL TERROR ERRANTE/Música/Music Box/Music Box has not had EventInstance.set3DAttributes() called on it yet!  
UnityEngine.Debug:LogWarningFormat (string,object)

and

[FMOD] FMOD\_OS\_Net\_Listen : Cannot listen for connections, port 9264 is currently in use.

Best Regards

---

<div class="post-metadata">

**Author:** ![Connor\_FMOD](https://yyz2.discourse-cdn.com/flex036/user_avatar/qa.fmod.com/connor_fmod/32/3685_2.png) [@Connor\_FMOD](https://qa.fmod.com/u/Connor_FMOD)\
**Post date:** [September 3, 2024, 4:18am UTC](https://qa.fmod.com/t/stop-an-instance-in-unity/22010/10 "2024-09-03T04:18:24Z")

</div>

> [@AntvilStudios](#):
>
> the problem with replacing old code with that code is that all the instances independent of emitters stop playing.

I see, maybe you could create an overload function. The important thing is getting the reference to the emitter event instance rather than creating a new one.

> [@AntvilStudios](#):
>
> If i write this (EventInstance as _My instance_:  
> **eventInstances.Add(musicBoxEmitter._My instance_)**  
> return emitter._My instance_

Sorry, I am unsure what you are trying to do here.

> [@AntvilStudios](#):
>
> [FMOD] Instance of Event event:/EL TERROR ERRANTE/Música/Music Box/Music Box has not had EventInstance.set3DAttributes() called on it yet!

Please refer to this documentation: [Unity Integration | Scripting API Reference - RuntimeManager](https://fmod.com/docs/2.02/unity/api-runtimemanager.html#createinstance).

> [@AntvilStudios](#):
>
> Cannot listen for connections, port 9264 is currently in use.

This can be caused if multiple applications are trying to use the same port. Can you make sure there aren’t multiple FMOD systems running and try restarting your PC.
