Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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?

share|improve this question

2 Answers 2

up vote 4 down vote accepted

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

public class GameSystem : MonoBehavior
{
  private GameSystem m_Instance;
  public GameSystem Instance { get { return m_Instance; } }

  void Awake()
  {
    m_Instance = this;
  }

  void OnDestroy()
  {
    m_Instance = null;
  }

  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.

share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.