22
23

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Unity] ゲームの進行を管理するGameManagerの簡単な例

Posted at

こういうことができる

gameManager.gif

GameManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public enum GameState{
	Start,
	Prepare,
	Playing,
	End
}

public class GameManager : MonoBehaviour {

	public static GameManager Instance;

	// 現在の状態
	private GameState currentGameState;


	// 例

	public Text label;
	public Button button;

	void Awake(){
		Instance = this;
		SetCurrentState (GameState.Start);
	}


	// 外からこのメソッドを使って状態を変更
	public void SetCurrentState(GameState state){
		currentGameState = state;
		OnGameStateChanged (currentGameState);
	}

	// 状態が変わったら何をするか
	void OnGameStateChanged(GameState state){
		switch (state) {
		case GameState.Start:
			StartAction ();
			break;
		case GameState.Prepare:
			StartCoroutine (PrepareCoroutine ());
			break;
		case GameState.Playing:
			PlayingAction ();
			break;
		case GameState.End:
			EndAction ();
			break;
		default:
			break;
		}
	}

	// Startになったときの処理
	void StartAction(){
	}

	// Prepareになったときの処理
	IEnumerator PrepareCoroutine(){
		label.text = "3";
		yield return new WaitForSeconds(1);
		label.text = "2";
		yield return new WaitForSeconds(1);
		label.text = "1";
		yield return new WaitForSeconds(1);
		label.text = "";
		SetCurrentState (GameState.Playing);
	}
	// Playingになったときの処理
	void PlayingAction(){
		label.text = "ゲーム中";
	}
	// Endになったときの処理
	void EndAction(){
	}
}

外部スクリプトからの状態の変更の仕方

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ButtonEvent : MonoBehaviour {

	public void OnStartButton(){
		GameManager.Instance.SetCurrentState (GameState.Prepare);
	}
}

22
23
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
23

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?