• 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 Msurdej · Dec 04, 2012 at 02:59 AM · c#audiowaitforseconds

Every few seconds, play an audio clip

Working on a game, where every few seconds, I want an object to play a sound. I'm using WaitForSeconds, but I'm getting some errors.

 using UnityEngine;
 using System.Collections;
 
 public class Carsound : MonoBehaviour {
     
     public AudioClip awoogah;
     public int carwait = 10;
     // Use this for initialization
     void Start () {
     
     }
     
     // Update is called once per frame
     void Update () 
     {
         yield return new WaitForSeconds (carwait);
 
         {
             audio.PlayOneShot(awoogah);    
             Debug.Log("ChOO-ChOO");
         }
         
     
     }
 }

Any help would be greatly appreicated!

Comment
Add comment · Show 3
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 prototype7 · Dec 04, 2012 at 04:53 AM 1
Share

Try this, but you have to change startPlay to true,

     public AudioClip awoogah;
     private bool startPlay = false;
     
     // Update is called once per frame
     void Update () 
     {
         if(startPlay){
             StartCoroutine(PlaySomeSound(10.0F));
             startPlay = false;
         }
     }
     
     IEnumerator PlaySomeSound(float carWait)
     {
         yield return new WaitForSeconds(carWait);
         audio.PlayOneShot(awoogah);
     }
avatar image fafase · Dec 08, 2012 at 08:07 AM 0
Share

This would actually result in a weird situation as you would start a new coroutine on each frame. You need to set startPlay back to false at some point.

avatar image prototype7 · Dec 08, 2012 at 08:49 AM 0
Share

you are right fafase, i updated the code

3 Replies

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by MarkFinn · Dec 04, 2012 at 05:27 AM

You'd be better off moving the entire thing to a coroutine I reckon. It'll give you a lot more flexibility. (Also, you cannot yield from any of the standard Unity Methods.

 using UnityEngine;
 using System.Collections;
 
 public class Carsound : MonoBehaviour {
 
     public AudioClip awoogah;
     public int carwait = 10;
     bool keepPlaying=true;
     
     void Start () {
         StartCoroutine(SoundOut());
     }
     
     IEnumerator SoundOut()
     {
         while (keepPlaying){
             audio.PlayOneShot(awoogah);  
             Debug.Log("ChOO-ChOO");
             yield return new WaitForSeconds(carwait);
         }
     }
 }
Comment
Add comment · Show 2 · 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 Eric5h5 · Dec 04, 2012 at 08:01 AM 0
Share

You can yield in nearly all of the standard Unity methods, aside from Update-related functions (FixedUpdate, LateUpdate etc.) and Awake.

avatar image Msurdej · Dec 08, 2012 at 12:49 AM 0
Share

Got it to work. Thanks $$anonymous$$arkFinn and all who posted.

avatar image
0

Answer by Neo.Yang · Dec 04, 2012 at 07:09 AM

Hi,Msurdej!

Few days ago, I faced a similar problem like yours. actually. the [ExecutionOrder][1] --> "Normal coroutine updates are run after the Update function returns. A coroutine is function that can suspend its execution (yield) until the given given YieldInstruction finishes."

Make it to easy understand, update method running every frame,the coroutine will follow, but the frame rate is not stable. So the time will not always accurate.

The solution is that you need a independent timer, for me I choosed the fixedUpdate Method, if you didn't change the Time.deltaFixedTime(Defalut is 0.02s,You can check the [Time Manager][2]). So you can write your script like this :

 float fixedTimer = Time.fixedDeltaTime;
 float accumulateTime = 0;
 int carwait =10;
 
 
 void fixedUpdate()
 {
     accumulateTime += fixedTimer;
     // Some times the system round algorithm will failed. use this to make sure the time always be accurate.
     accumulateTime = (float)System.Math.Round(accumulateTime,3);
     if(accumulateTime >= carwait)
     {
         //Play the audio...
         accumulateTime -= carwait;
     }
 }

For now, my script is work fine. if you got new ideas and work precisely , plz tell me. [1]: http://docs.unity3d.com/Documentation/Manual/ExecutionOrder.html [2]: http://docs.unity3d.com/Documentation/Components/class-TimeManager.html

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
2

Answer by fafase · Dec 04, 2012 at 07:48 AM

Fact is you cannot yield in Update. So:

 void Update () {
        yield return new WaitForSeconds (carwait);<- Here error
 
        {<-Why is this by the way?
          audio.PlayOneShot(awoogah);  
          Debug.Log("ChOO-ChOO");
        }
 }

The most simple way is InvokeRepeating:

 void Start(){
      InvokeRepeating("PlaySound",0.001f,2f);
 }
 void PlaySound(){
     audio.Play();
 }

The first parameter is the function to call. The second is when you want the first call to happen. 0 is buggy and call the function twice so instead give a small value like I did. The last parameter is the frequency of calls. In my case every 2 seconds. Make sure your sound is not looping.

Now other way. even easier!!! Your sound could be the length you need (you could use Audacity). So for instance it goes Choo-chooo.....silence...... Then all you have to do is attach the AudioSource to your train (I guess it is a train), tick PlayOnAwake and tick Loop. And that is it.

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

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

The best place to ask and answer questions about development with Unity.

To help users navigate the site we have posted a site navigation guide.

If you are a new user to Unity Answers, check out our FAQ for more information.

Make sure to check out our Knowledge Base for commonly asked Unity questions.

If you are a moderator, see our Moderator Guidelines page.

We are making improvements to UA, see the list of changes.



Follow this Question

Answers Answers and Comments

14 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

Related Questions

Multiple Cars not working 1 Answer

Distribute terrain in zones 3 Answers

play audio for few seconds on key hit 1 Answer

About WaitForSeconds 1 Answer

Random wait times 1 Answer


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