- Home /
Creating code to end a level once all objects are collected
I'm trying to finish a level that ends and goes to the next stage once six objects are collected. These objects are collected simply by deactivating them once the player comes in contact with them. What coding will I need to make this happen?
Answer by Deathdefy · Nov 05, 2013 at 11:12 PM
Every time one of the objects is collected you need to increment a certain value. You can use a static integer if you want and when the player steps into the trigger you can add to it. Make sure your colliders IsTrigger is set to true
static int itemsCollected = 0;
private void OnTriggerEnter(Collider col)
{
itemsCollected++;
}
Then in another script you can have it handle the changing of levels.
private void Update()
{
if(ScriptName.itemsCollected >= 6)
Application.LoadLevel("levelName");
}
Answer by aldonaletto · Nov 05, 2013 at 11:45 PM
A simple solution is to attach a script like this to every key object:
public static var keyObjects: int = 0; // how many key objects are in scene
function Awake(){
// automatically count this object when it's created:
keyObjects++;
}
function OnDisable(){
// decrement counter when object gets deactivated:
keyObjects--;
}
You can poll the variable keyObjects in another script (attached to any object in scene, usually an empty one), and load the next level when it reaches zero. Supposing that the script above is saved as KeyObjScript.js, the polling script could be something like this:
public var nextLevel: String; // define here the next level name
function Update(){
if (KeyObjScript.keyObjects == 0){
Application.LoadLevel(nextLevel);
}
}
Your answer
Follow this Question
Related Questions
Key Pick up 2 Answers
how to make a save/load game script 2 Answers
Using variables and classes of C# in Javascript? 1 Answer
Problem with getting a value from a enum 2 Answers
Adding component to component 1 Answer