So, in making my brick breaker game, I wanted to add some additional features to it. One was to add 3 lives to each level. To do this, I needed to create a function that allowed my LevelManager to track the lives and if the lives == 0, then run my LoadLevel. Like this…
public static void SubtractLife(){
lifes--;
if(LevelManager.lifes == 0){
LoadLevel("lose");
}
}
So, when I went into my LoseCollider, I removed its ability to change level and replaced it with SubtractLife. Like this…
void OnTriggerEnter2D(Collider2D trigger){
LevelManager.SubtractLife();
Ball.has_started = false;
}
Well it didn’t like LoadLevel(“lose”) because it wasn’t a static method of LevelManager and so needed an object reference. Well I just made it static, as I figured why not, I can then easily access it from anywhere for level change functions. The ball, special events, w/e; I can call it when I need it. But then my buttons stopped working. They called on the LoadLevel method and I input the string in my inspector. Now it says “missing” before the method in the inspector. Like this…
So it was a simple fix, I just created a new method call LoadLevelButton that wasn’t static…
public void LoadLevelButton(string name){
Application.LoadLevel(name);
}
So, now I select that in the inspector and input my own string. My question is, and what I would like help on is am I doing it right? Should I make the LoadLevel function static, or am I just doing it wrong in creating multiple ways to accomplish the same thing? I guess what I’m really asking is why can’t my SubtractLife function call on LoadLevel unless LoadLevel is static?
using UnityEngine;
using System.Collections;
public class LevelManager : MonoBehaviour {
private static int lifes = 3;
public static void LoadLevel(string name){
Brick.brickCount = 0;
Application.LoadLevel(name);
}
public void LoadLevelButton(string name){
Brick.brickCount = 0;
Application.LoadLevel(name);
}
public static void LoadNextLevel(){
Application.LoadLevel(Application.loadedLevel + 1);
}
public static void BricksDestroyed(){
if(Brick.brickCount<=0){
LoadNextLevel();
LevelManager.LifeAdd();
}
}
public static void LifeAdd(){
lifes = 3;
}
public static void SubtractLife(){
lifes--;
if(LevelManager.lifes == 0){
LoadLevel("lose");
Ball.has_started = false;
}
}
}
using UnityEngine;
using System.Collections;
public class LoseCollider : MonoBehaviour {
void OnTriggerEnter2D(Collider2D trigger){
print (trigger);
LevelManager.SubtractLife();
Ball.has_started = false;
}
}