• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by embodied_computation · Aug 18, 2018 at 08:27 PM · audiosourcefadestate machine

Help! Trying to code basic state machine to fade an audio source, stop it, and then restart it!

I am new to C# and am building a simple VR audio game. I'm am looking to code a very simple interaction that works like this pseudocode:


OnTriggerStay () {

(if audio source isn't playing)

{ play audio source }

}

OnTriggerExit() {

Fade the audio source volume. Once volume is 0, stop the audio source. Once audio source is stopped, then reset its volume to 1.

}


Essentially, this allows a player to hold their controller inside of a sphere and play a sound. If they move their controller out of the sphere then the sound should appear to fade out and then stop playing. As soon as they hold their controller in the sphere again, the sound should start playing from the beginning.


I am unsure of how to properly code the audio fade, stop and reset. I successfully used Mathf.Lerp to fade the volume from 1 to 0 over a period of 0.5 seconds. But I am unsure of how to properly code the rest of the states. Here is my current progress:

 public class SoundOnHold : MonoBehaviour {
  
     AudioSource currentSample;
     bool exitingSphere = false;
     float startingVolume = 1f;
     float fadeDuration = 0.4f;
     float rate;
  
     bool sampleStopped;
  
     private void Start()
     {
         currentSample = GetComponent<AudioSource>();
     }
  
     void OnTriggerStay(Collider other)
     {
         if (!currentSample.isPlaying)
         {
             currentSample.Play();
         }
     }
  
     void OnTriggerExit(Collider other)
     {
         exitingSphere = true;
     }
  
     private void Update()
     {
         if (exitingSphere == true)
         {
             if (rate < 1)
             {
                 rate += Time.deltaTime / fadeDuration;
                 currentSample.volume = Mathf.Lerp(1f, 0f, rate);
             }
  
             if (currentSample.volume == 0f)
             {
                 currentSample.Stop();
                 sampleStopped = true;
             }
  
             if (sampleStopped = true)
             {
                 currentSample.volume = 1f;
                 exitingSphere = false;
             }
         }
     }
 }

I used very basic boolean and if statements to create the different states but it isn't working and I have a feeling that my logic is really really bad. Any advice would be greatly appreciated! Perhaps I should be using some coroutines?

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

2 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by rainChu · Aug 18, 2018 at 11:12 PM

Coroutines would be the way to go here, yes. It's not only a lot simpler to read the code when you use them, but also more efficient, because the update method only will be called while fading.

Here is how I would do it:

 IEnumerator fadeCoroutine;

 [SerializeField] AnimationCurve fadeOutCurve; // Adjust this in the editor to your liking
 [SerializeField] float fadeTimeInSeconds = 1f; // Adjust to your liking

 // Using OnTriggerEnter here instead of OnTriggerStay. I'm doing this
 // because it's a bit more efficient.
 // Be sure your AudioSource is set to loop, or this will have the side effect of
 // causing it to stop after one play
 void OnTriggerEnter(Collider other)
 {
     if ( fadeCoroutine != null )
     {
         StopCoroutine( fadeCoroutine );
         fadeCoroutine = null;
     }
     currentSample.volume = 1f;
     currentSample.Play();
 }

 void OnTriggerExit( Collider other )
 {
     if ( fadeCoroutine != null )
         StopCoroutine( fadeCoroutine );
     StartCoroutine( fadeCoroutine = DoFadeOut() );
 }

 IEnumerator DoFadeOut( )
 {
     var evalTime = 0f;
     while ( evalTime < 1f )
     {
         evalTime += Time.deltaTime * fadeTimeInSeconds;
         currentSample.volume = fadeOutCurve.Evaluate( evalTime );
         yield return null;
     }
     currentSample.volume = 0f;
     currentSample.Stop();
 }


Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by ignacevau · Aug 18, 2018 at 11:30 PM

A decent answer has already been provided by @rainChu but I would like to point out why your code didn't do the trick.


The main problem you have is simply because you wrote in the end of your code

   if (sampleStopped = true)
   {
       currentSample.volume = 1f;
       exitingSphere = false;
   }

However, this always returns true, instead you should have written sampleStopped == true


One more thing: Since sampleStopped stays true,

 currentSample.volume = 1f;
 exitingSphere = false;

gets called every frame, you could simply solve that by using this:

      if (currentSample.volume == 0f)
      {
          currentSample.Stop();
          currentSample.volume = 1f;
          exitingSphere = false;
      }
Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image rainChu · Aug 18, 2018 at 11:32 PM 0
Share

Nice catch! I didn't notice that, at first.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

91 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

How to smoothly fade audio without any pops? Source.volume is correct, but the sound itself seems to update inconsistently. 1 Answer

How to fade in-out groups of audio sources? 0 Answers

Fade out an AudioSource 1 Answer

What is the script code on how to trigger a song for the player to Listen to? 2 Answers

Assertion failure in AudioManager.cpp? 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges