- Home /
Problem with static variables
Hi
I'm creating a game with different levels. I have a Main Menu and also a level selection menu. I also have 2 scripts. I'd like to know how it is possible to only select the levels in the level selection menu that you already have finished. I've tried it with static variables but now I know that static variables reset if you switch a scene.
This is my Move Around Script:
var speed = 6.0; var JumpSpeed = 8.0; var gravity = 20.0; private var dead = false; private var moveDirection = Vector3.zero; private var grounded : boolean = false; var myClip : AudioClip; static var Level1Enabled = true; static var Level2Enabled = false;
function OnControllerColliderHit(hit: ControllerColliderHit) // Fall To Dead { if(hit.gameObject.tag =="Fallout") { dead = true; HealthControl.LIVES -=1; } //End Level if(hit.gameObject.tag =="End1") { Level2Enabled = true; Application.LoadLevel(3); // selection menu
} }
Script atached to the gui.text in the selection menu for level 2.
var level2Finished = MoveAround.Level2Enabled; function OnMouseEnter() { if(level2Finished) { renderer.material.color = Color.green; } } function OnMouseExit() { renderer.material.color = Color.white; }
function OnMouseUp() { if(level2Finished) { Application.LoadLevel(4); } }
Answer by karl_ · Mar 22, 2011 at 11:19 PM
If you're going to allow players to exit and resume the game, I'd look into the PlayerPrefs class ( http://unity3d.com/support/documentation/ScriptReference/PlayerPrefs.html ). This will allow you to save variables through different playthroughs. So for example, if you finish level 1 do something like :
function onLevelComplete()
{
PlayerPrefs.SetInt("levelsComplete", 1);
}
So for this example levelsComplete is an int representing the amount of levels complete. Your menu script would check something like this:
if(PlayerPrefs.GetInt("levelsComplete") >= 1)
// makeLevelOneClickable
Good answer. Also, if you have a problem with things reseting when changing a scene, use DontDestroyOnLoad.