Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • 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 Mischa.Silden · Jun 22, 2011 at 06:44 AM · c#changemusicienumeratorcycle

Cycle things with one key

Hi! I want to cycle music with same key (in my case, letter "m") but I don't know how to write the function in.

Now I can crossfade music with two different keys but that is not I want. What should I do?

Help would be much appreciated :) Here is the code:

 using UnityEngine;
 using System.Collections;
 
 public class scr_MusicController : MonoBehaviour
 {
 
     void Update()
     {
         if (Input.GetKeyDown("m"))
         {
             StartCoroutine("ChangeMusic1");
         }
         if (Input.GetKeyDown("n"))
         {
             StartCoroutine("ChangeMusic2");
         }
     }
     private IEnumerator ChangeMusic1()
     {
         float fTimeCounter = 0f;
 
         while (!(Mathf.Approximately(fTimeCounter, 1f)))
         {
             fTimeCounter = Mathf.Clamp01(fTimeCounter + Time.deltaTime);
             transform.FindChild("aud_Normal").audio.volume = 1f - fTimeCounter;
             transform.FindChild("aud_Retro").audio.volume = fTimeCounter;
             yield return new WaitForSeconds(0.02f);
         }
 
         StopCoroutine("ChangeMusic1");
     }
     private IEnumerator ChangeMusic2()
     {
         float fTimeCounter = 0f;
 
         while (!(Mathf.Approximately(fTimeCounter, 1f)))
         {
             fTimeCounter = Mathf.Clamp01(fTimeCounter + Time.deltaTime);
             transform.FindChild("aud_Retro").audio.volume = 1f - fTimeCounter;
             transform.FindChild("aud_Normal").audio.volume = fTimeCounter;
             yield return new WaitForSeconds(0.02f);
         }
 
         StopCoroutine("ChangeMusic2");
     }
 }
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

1 Reply

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

Answer by GuyTidhar · Jun 22, 2011 at 07:41 AM

 public class scr_MusicController : MonoBehaviour
 {     
    public  string[]      sourceNames = new string[] { "aud_Normal", "aud_Retro"};    
    private AudioSource[] audioSources;
    private int           currentSound;
    
    void Start()
    {
        // Set up the list of audioSources to be switched         
        if ( sourceNames != null && sourceNames.Length > 0 )
        {
           audioSources = new AudioSource[sourceNames.Length];
           for(int i=0; i<sourceNames.Length; i++)
           {
             audioSources[i] = transform.FindChild(sourceNames[i]).audio;
           }
           currentSound = 0;
           enabled = true;         
        }
        else
        {
           Debug.LogError("No AudioSource names set - disabling script");
           enabled = false;         
        }     
    }
        
    void Update()
    {
        if (Input.GetKeyDown("m") )
        {             
           StopCoroutine("ChangeMusic");
           StartCoroutine("ChangeMusic");
        }
    }          

    private IEnumerator ChangeMusic()
    {
        float fTimeCounter = 0f;
        int oldSound = currentSound;
        int nextSound = (currentSound + 1) % audioSources.Length;
 
        currentSound = nextSound;
            
        while (!(Mathf.Approximately(fTimeCounter,1f)))
        {
            fTimeCounter = Mathf.Clamp01(fTimeCounter + Time.deltaTime);
            // I fade off any sound which is not our target sound (the "nextSound")
            // since you might be cycling a sound while the last one or more crossfades
            // were not done yet
            for(int i=0; i<audioSources.Length; i++)             
            {
                if ( i != nextSound )
                   audioSources[i].volume = 1f - fTimeCounter;
                else
                   audioSources[i].volume = fTimeCounter;             
            }
    
            yield return new WaitForSeconds(0.02f);
         }
 
         // You do not need to stop a coroutine at the end of its scope - the end of the 
       // scope means the coroutine is about to stop processing. You only use 
       // StopCoroutine when you want it to stop in the middle or processing
     } 

}

Comment
Add comment · Show 3 · 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 GuyTidhar · Jun 22, 2011 at 07:43 AM 1
Share

(This script should enable you to crossfade between several audioSources). I'm assu$$anonymous$$g you FindChild function returns a script that has the parameter audio of type AudioSource...

avatar image Mischa.Silden · Jun 22, 2011 at 07:55 AM 0
Share

Whoa! Didn't think that the script required that much modification. It works now as intended! Thanks for your time and effort :)

avatar image GuyTidhar · Jun 22, 2011 at 08:42 AM 1
Share

I added a more generic support so you could fade not only 2, that's why it got a bit more complex

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.

Follow this Question

Answers Answers and Comments

3 People are following this question.

avatar image avatar image avatar image

Related Questions

Distribute terrain in zones 3 Answers

Multiple Cars not working 1 Answer

Timer variable set to zero 2 Answers

Why is instantiated animator prefabs are not working properly? 2 Answers

Music code not playing music. 3 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