15
\$\begingroup\$

As far as Iknow in Unity, every script must be attached to an object. But what is the case with global scripts? For example in a tetris-like game to which object should I attach the element spawner and mover scripts? Or should a the element handle its movement for itself? Is there any best practice for this problem?

\$\endgroup\$

3 Answers 3

17
\$\begingroup\$

To expand on Tetrad's answer, consider a script like this:

public class GameSystem : MonoBehavior
{
  public static GameSystem Instance { get; private set; }

  void Awake()
  {
    if (Instance != null) {
      Debug.LogError("There is more than one instance!");
      return;
    }

    Instance = this;
  }

  void Update()
  {
    // global game update logic goes here
  }

  void OnGui()
  {
    // common GUI code goes here
  }

  // etc.
}

You can then create an object called "GameSystem" in the root of your scene. The only components it would have would be the built-in transform component (set its position to the origin, its rotation to identity, and its scale to one; not that it matters, but it's good practice). Attached the GameSystem component to that object.

You can now access your global object by simply using GameSystem.Instance.blah(). Its event handler methods are invoked automatically by Unity since it derives from MonoBehavior and exists as a component. You can add fields to it that reference other game objects or components and connect them in the Unity object hierarchy view.

Yes, this is all a little "weird." It can feel a little dirty to have to create an object (that even has a transform) which is always just a global singleton. It's what Unity requires to create global objects that get an Update message and are manipulable with the default Unity property editor, though.

\$\endgroup\$
2
  • \$\begingroup\$ Thanks for this answer. I agree it feels weird! and think there's very little info out there on this side of things. Could you perhaps recommend some reading materials on how best to approach these 'manager' type classes in unity? \$\endgroup\$
    – UpTheCreek
    Commented Jan 7, 2015 at 16:09
  • \$\begingroup\$ @UpTheCreek: I don't really know any. We mostly figured it out all on the job a couple years ago, but our current projects are on custom tech so I'm pretty out-of-date with Unity best practices these days. Sorry. \$\endgroup\$ Commented Jan 7, 2015 at 20:21
3
\$\begingroup\$

Just create a manager object that you put that script on. Maybe make a static variable for that script that you assign on Awake so you have easy global access to it.

\$\endgroup\$
0
\$\begingroup\$

This Unity tutorial shows how to create a singleton object.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .