728x90
* Commnad ํจํด: ๋ฉ์๋ ํธ์ถ์ ์ค์ฒดํ, ์ฆ ๊ฐ์ฒด๋ก ๊ฐ์ผ ๊ฒ.
: ํจ์ ํธ์ถ์ ๊ฐ์ฒด๋ก ๋ง๋ ์ด์ ๋ ๋์ปคํ๋ง์ผ๋ก ์ฝ๋๊ฐ ์ ์ฐํด์ง๊ธฐ ๋๋ฌธ.
ex) ์ ๋ ฅํค ๋ณ๊ฒฝ, ์คํ์ทจ์/์ฌ์คํ ๋ฑ์ ๊ธฐ๋ฅ์ ๋ง๋ค ๋ ์ฌ์ฉ.
1. Command ํจํด์์ด ๋ง๋ GetKey ๊ธฐ๋ฅ
using System.Collections;
using UnityEngine;
public class Player : MonoBehaviour
{
[SerializeField] private GameObject shield;
[SerializeField] private GameObject cannon;
[SerializeField] private Transform firePos;
void Update()
{
if (Input.GetKeyDown("a"))
{
Attack();
}
else if(Input.GetKeyDown("b"))
{
Defense();
}
}
private void Attack()
{
Debug.Log("Attack");
Instantiate(cannon, firePos.position, firePos.rotation);
}
private void Defense()
{
Debug.Log("Defense");
shield.SetActive(true);
StartCoroutine(Defense(0.5f));
}
private IEnumerator Defense(float time)
{
yield return new WaitForSeconds(time);
shield.SetActive(false);
}
}
2. Command ํจํด์ผ๋ก ๋ง๋ GetKey ๊ธฐ๋ฅ
using UnityEngine;
using UnityEngine.UI;
public class PlayerCommand : MonoBehaviour
{
[SerializeField] private Text text1;
[SerializeField] private Text text2;
private bool isCommand;
CommandKey btnA, btnB;
private void Start()
{
isCommand = true;
SetCommand();
}
//setCommand() ๋ฉ์๋๋ฅผ ํตํด ๋ฒํผ์ ๋๋ฅด๋ฉด ์ด๋ค ๋์์ ์ํํ ์ง๋ฅผ ๊ฐ ๋ฒํผ์ ๋ฑ๋ก
private void SetCommand()
{
if (isCommand)
{
btnA = new CommandAttack();
btnB = new CommandDefense();
isCommand = false;
text1.text = "A - Attack";
text2.text = "B - Defense";
}
else
{
btnA = new CommandDefense();
btnB = new CommandAttack();
isCommand = true;
text1.text = "A - Defense";
text2.text = "B - Attack";
}
}
//๋ฒํผ์ ๋๋ฅด๋ฉด ๋จ์ง Execute() ๋ง ํธ์ถ
private void Update()
{
if (Input.GetKeyDown("a"))
{
btnA.Execute();
}
else if (Input.GetKeyDown("b"))
{
btnB.Execute();
}
}
}
ํค๋ฅผ ๋ฐ๊ฟ ๋ฒํผ์ ํ๋๋ง ๋ค์ด์ SetCommand() ํจ์๋ฅผ ๋ฌ์์ค๋ค.
SetCommand ๋ฒํผ์ ๋๋ฅผ ๋๋ง๋ค isCommand ๊ฐ์ด ๋ฐ๋๋ฉฐ ์๋์ ๊ฐ์ด ๋์ํ๋ค.
isCommand ๊ฐ true ์ผ ๋ btnA - Attack / btnB - Defense
isCommand๊ฐ false ์ผ ๋ btnA - Defense / btnB - Attack
์ด๋ ๊ฒ GetKey ๊ธฐ๋ฅ์ ๋ฐ๊ฟ ์ ์๋ค.
using UnityEngine;
public abstract class CommandKey
{
public virtual void Execute() { }
}
public class CommandAttack : CommandKey
{
public override void Execute()
{
Attack();
}
private void Attack()
{
Debug.Log("Attack");
}
}
public class CommandDefense : CommandKey
{
public override void Execute()
{
Defense();
}
private void Defense()
{
Debug.Log("Defense");
}
}
728x90
'๐ Computer Science > Design Pattern' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Unity][๋์์ธ ํจํด] Simple Factory Pattern(์ฌํ ํฉํ ๋ฆฌ ํจํด) (0) | 2023.09.13 |
---|---|
[Unity][๋์์ธ ํจํด] Component Pattern (0) | 2023.09.12 |
[C#][Unity][๋์์ธ ํจํด] Strategy Pattern(์ ๋ต ํจํด) (0) | 2023.09.05 |
[Unity][๋์์ธ ํจํด] Observer Pattern (0) | 2023.09.03 |