Change the position of a sound (set3DAttributes)

Hey guys,

What I want to do
Is it possible to change the game object the sound is coming from, even though the script is attached to a different game object? For example with the 3D attributes I can add the sound to the same game object the script is attached to. But can this be changed?

The use case
I have a 3rd person shooter and the shooting is done with a raycast. Whenever the ray hits something, I want a sound be played from the game object that was hit. Of course I could attach the sound to the hit game object itself and just call the script as soon as it is being hit, but that requires to add the script to all possible game objects in the world. So I thought it would be smarter to just add the sound to the raycast and move its position to the according game object that was hit.

The code

Ray shootRay;
RaycastHit shootHit;
// Shoot ray and see if it hits something
if(Physics.Raycast (shootRay, out shootHit))
{
// Load the sound linked in the inspector
Impact = FMODUnity.RuntimeManager.CreateInstance(ImpactEvent);
// Attach sound to game object
Impact.set3DAttributes(FMODUnity.RuntimeUtils.To3DAttributes(shootHit.collider.gameObject));
// Start the event
Impact.start();
}

Unfortunately it’s not working. Is it even possible to add the sound to a different game object than the script? And if so, how to change the 3DAttributes accordingly?

What you have there should work, as long as you are telling the Ray where to go, eg.

ray = new Ray(origin, direction);

For an impact sound you might be better off using FMODUnity.RuntimeManager.PlayOneShot(), but what you have done isn’t wrong, just make sure to release the instance when you are done with it.

1 Like

Thanks for answering. You’re right, working with a OneShot would be better in this case. But as I need to manipulate a parameter before the playback I had to manually trigger the sound this way. Thanks for the release hint though. Everything is working properly now:)