I have a Manager class and it has lots of variables so I can reference it when I need it.
Will this reduce the performance ? or should I define it
public class Controller: MonoBehaviour
{
public GameObject Manager;
}
public class GetController : MonoBehaviour
{
public GameObject Controller ;
void dosomthing(){
var Ma = Controller.Getcomponent<Controller>().Managet
}
}
CodePudding user response:
TLDR; Getcomponent()
calls are expensive. It is OK if used once/rarely, but starts to have an effect when called continiously.
Store a reference (define) to it:
public class GetController : MonoBehaviour
{
// Will show up in unity's inspector.
// Drag-and-Drop the gameObject with the 'Controller' component attached to it.
[SerializeField]
private Controller yourController ;
void Dosomthing(){
var Ma = yourController.Manager
}
}
Also, most things in Unity can be exposed to the Inspector as long as it is serializable.
You can expose a Controller
field to the inspector, and drag-drop the same GameObject.
This lets you skip a GetComponent
call and another define.
CodePudding user response:
I suggest using a singleton
pattern for managers.
public class GameManager : MonoBehaviour
{
public static GameManager singleton; // define variable as singleton
public int score = 2; // for example...
private void Start() => singleton = this; // setup single user class instance
}
And in the player class or any other class, call it without redefining it.
public class Player : MonoBehaviour
{
public void AddScore() => GameManager.singleton.score = 1; // add score to manager
}