2 minute read

Unity:プレイヤーの体力や状態に応じて、プレイヤーの情報を変更する

作ってるゲームアプリで、プレイヤーの状態を管理する必要が出てきたため、

既存コードをリファクタリングしつつガリガリした。

参考にしたのはStateパターン。

こうしたらもっと良くなるよ、それStateパターン違うぜよって方がいたら、

優しくご教示頂ければ幸いです。

Player Class


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

public class Player : MonoBehaviour
{

	private LifeState state;

	[SerializeField]
	private GameObject explosionParticle = null;

	CameraController cameraController;
	SceneController sceneController;
	SpriteRenderer spriteRenderer;


	void Awake()
	{
		state = new HpState.HealthState();
		cameraController = GameObject.FindWithTag("CameraController").GetComponent<CameraController>();
		sceneController = GameObject.FindWithTag("SceneController").GetComponent<SceneController>();
		spriteRenderer = this.GetComponent<SpriteRenderer>();
	}

	void OnCollisionEnter2D(Collision2D other)
	{
		if (other.gameObject.tag == "Enemy") {
			cameraController.shake();

			if (state.nowState == "dead") {
				sceneController.gameOver();
				return;
			}

			changeState(state.nextState());
			spriteRenderer.color = new Color(state.red, state.green, state.blue, state.alpha);
		}

	}

	void changeState(LifeState lifestate) {
		state = lifestate;
	}

}

HpState Class


public class HpState {

	public class HealthState : LifeState {
		public string nowState { get { return "health"; } }
		public float red { get { return 1.0f; } }
		public float green { get { return 1.0f; } }
		public float blue { get { return 1.0f; } }
		public float alpha { get { return 1.0f; } }
		public LifeState nextState(){
			return new NormalState();
		}

	}

	class NormalState :LifeState {
		public string nowState { get { return "normal"; } }
		public float red { get { return 0.0f; } }
		public float green { get { return 1.0f; } }
		public float blue { get { return 0.0f; } }
		public float alpha { get { return 1.0f; } }
		public LifeState nextState(){
			return new DengerState();
		}

	}

	class DengerState : LifeState {
		public string nowState { get { return "danger"; } }
		public float red { get { return 1.0f; } }
		public float green { get { return 1.0f; } }
		public float blue { get { return 0.0f; } }
		public float alpha { get { return 1.0f; } }
		public LifeState nextState(){
			return new DeadState();
		}

	}

	class DeadState : LifeState {
		public string nowState { get { return "dead"; } }
		public float red { get { return 1.0f; } }
		public float green { get { return 0.0f; } }
		public float blue { get { return 0.0f; } }
		public float alpha { get { return 1.0f; } }
		public LifeState nextState(){
			return new DeadState();
		}

	}

}


LifeState Interface


public interface LifeState {

	string nowState { get; }
	float red { get; }
	float green { get; }
	float blue { get; }
	float alpha { get;}

	LifeState nextState();

}