Is there a way to access a singleton method directly instead of going through it’s instance?
// Instead of doing this,
GameManager.Instance.DealDamage(Target);
// Is there a way to do this?
GameManager.DealDamage(Target);
=====
GameManager.cs
using UnityEngine;
using System.Collections;
public class GameManager: MonoBehaviour {
// Singleton
private static GameManager instance;
public static GameManager Instance {
get {
return instance ?? (instance = GameObject.FindObjectOfType(typeof(GameManager)) as GameManager);
}
}
public void DealDamage (GameObject Target) {
// Deal damage to the passed target
}
}
If that’s the behavior you want you should just use static methods, with static (class) variables if needed to store state.
public static void DealDamage (GameObject Target)
If you don’t need to hook into Unity’s standard functions like Awake, Start, Update etc, then don’t inherit from MonoBehavior.
If you do want to hook into the Unity functions you can use a singleton instance to update your static variables, without needing to provide public access to the instance.
For those wondering, this is how I ended up doing it.
=======
GameManager.cs → Attached to GlobalScripts prefab (empty GameObject)
using UnityEngine;
using System.Collections;
public static class GameManager {
// Event for triggering damage to an object
public delegate void OnDamageEvent(GameObject Go, int DamageAmount);
public static event OnDamageEvent OnDamage;
// Deals damage to the target
public static void DealDamage (GameObject Target, int DamageDealt) {
OnDamage(Target, DamageDealt);
}
}
=======
In the Enemy Controller
// Attack the target
protected override void Attack () {
anim.Play("Attack");
// Deal damage to target
GameManager.DealDamage(Target, Damage);
}
=======
In the possible target controllers
void Awake () {
GameManager.OnDamage += OnDamage;
}
// Damage event method
protected void OnDamage (GameObject Target, int DamageAmount) {
// Check if we have this game object
if (Target == gameObject) {
TakeDamage(DamageAmount);
}
}