c# - Unity-Music continues in different scenes, and turned off/on every scene -


in unity project, there different menus, , each menu different scene. each scene has button controlling music.

public void musictoggle(gameobject off){         if (playerprefs.getint ("music") == 1) {             musicplayer.stop ();             debug.log ("stop 2");             playerprefs.setint ("music", 0);             off.setactive(true);         }         else {             musicplayer.play ();             debug.log ("play 2");             playerprefs.setint ("music", 1);             off.setactive (false);         }     } 

this musictoogle function. in every scene music restarts, , in every scene when want turn on/off music, click button deploys code. however, don't want music restart every scene change, want resume, , want able control music(turn on/off) in every scene. how can ?

my answer assumes musicplayer variable type of audiosource.

there 2 ways this:

1.instead of using musicplayer.stop stop music,

use musicplayer.pause(); pause music use musicplayer.unpause(); un-pause it. make sure music resumes instead of restarting it.

in case, use dontdestroyonload(gameobject); on each gameobject audiosource not destroyed when on next scene.


2.store audiosource.time value. load next time apply audiosource before playing it.

you can use playerprefs prefer store json , datasaver class.

save:

audiosource musicplayer; audiostatus astat = new audiostatus(musicplayer.time); //save data audiostatus file named audiostat_1 datasaver.savedata(astat, "audiostat_1"); 

load:

audiosource musicplayer; audiostatus loadeddata = datasaver.loaddata<audiostatus>("audiostat_1"); if (loadeddata == null) {     return; } musicplayer.time = loadeddata.audiotime; musicplayer.play(); 

your audiostatus class:

[serializable] public class audiostatus {      public float audiotime;      public audiostatus(float currenttime)     {         audiotime = currenttime;     } } 

Comments

Popular posts from this blog

neo4j - finding mutual friends in a cypher statement starting with three or more persons -

php - How to remove letter in front of the word laravel -

minify - Minimizing css files -