- Home /
Code design issue
Hello! How do i best pass a class down as a reference to other classes? Say i have a main class that handles game over, restart game etc... How do i pass a reference to it to another class that make use of these methods? I now have a gui class that handles if the player chooses to restart or go back to the main menu. This class needs access to the main class, right now the gui class just finds the gameobject containing the main class but i want something cleaner like a constructor but they dont work well with monobehaviour apparently....
Answer by Raresh · Nov 14, 2016 at 08:13 PM
Just like the suggestion above, only without having to keep a reference in each game object...
https://unity3d.com/learn/tutorials/projects/2d-roguelike-tutorial/writing-game-manager
Implement the singleton pattern in your GameManager, it will be more useful this way. And less clunky.
Answer by Hanoble · Nov 14, 2016 at 08:10 PM
The Unity way would be in your UI class to have a reference to the GameManager, and then drag it in via the inspector. Essentially something like this:
Public class GameUI : Monobehaviour
{
//reference the game manager
public GameManager gm;
public void UpdateScore()
{
score.Text = gm.GetScore();
}
}
Answer by Aluxxi · Nov 14, 2016 at 08:39 PM
GameManager.cs
using UnityEngine;
public class GameManager : MonoBehaviour {
public void GameOver() {
Debug.Log("game over")
}
}
PlayerScript.cs
using UnityEngine;
public class PlayerScript : MonoBehaviour
{
public GameManager gm;
public int playerHealth = 3;
void Update()
{
if (playerHealth == 0) {
gm.GameOver();
}
}
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Illuminating a 3D object's edges OnMouseOver (script in c#)? 1 Answer