*Component Pattern: ๋ก์ง์ ๊ธฐ๋ฅ๋ณ๋ก ์ปดํฌ๋ํธ ํ๋ ๊ฒ.
ํด๋์ค๋ฅผ ๋ถ๋ฆฌํ๊ณ ๊ฐ๋ ์ฑ์ ๋์ด๊ณ Decoupling(๋ ์์ ์ธ ํ๋ฆ์ ๋ณด์ด๋ ๊ฒ) ์ํค๋ ๊ฒ์ ํ์ ํ์ฌ ๊ฐ๋ฐ์ ๋ง์ด ํด๋ณธ ์ฌ๋๋ค์๊ฒ๋ ์์ฐํ ๋ น์ ์๋ ์ต๊ด์ด๋ค. ์ด๋ฐ ๊ตฌ์กฐ์ ์ธ ๊ฐ์ ์์ ์ ์ ๋ฐฐ ๊ฐ๋ฐ์๋ค์ด ์ด๋ฏธ ์ปดํฌ๋ํธ ํจํด์ผ๋ก ๋ช ๋ช ํด ๋์๋ค.
ํนํ Unity ์ GameObject ๋ Component ํจํด์ด ์ ๋ฐ์๋์ด ์ค๊ณ๋ ํด๋์ค์ด๋ค. GetComponet Method ๋ก ๊ฐ๊ฐ์ Decoupling ๋ ํ์ ์ปดํฌ๋ํธ๋ค์ ๋ถ๋ฌ์ ์ฌ์ฉํ ์ ์๋ค.
์ ๋ํฐ๋ ์๋ก์ด ํ๋์ ์ถ๊ฐํ๋ ์ปดํฌ์ง์ (composition: ํฉ์ฑ) ๊ตฌ์กฐ๋ฅผ ์ฑ์ฉํ๋ค. ์ด ์ ์ ์์(Inheritance)๋ฅผ ํตํด ํ์ฅ๋๋ ์ค๋ธ์ ํธ ์งํฅ ํด๋์ค ๊ณ์ธต๊ณผ๋ ์์์ ๋ฌ๋ฆฌํ๋ค.
ex)
2๊ฐ ๊ฐ์ฒด๋ฅผ ๋ง๋ค๊ณ 1๊ฐ๋ ํ์ , 1๊ฐ๋ ์ด๋ํ๋ ์ฝ๋๋ฅผ ๋ง๋ ๋ค๊ณ ํด๋ณด์.
//๋์์ธ ํจํด ์ ์ฉ์ํ๊ณ ํ๋์ ์คํฌ๋ฆฝํธ์ ์์ฑํ์ ๋
using System.Collections;
using UnityEngine;
enum MOVE
{
MOVE_RIGHT,
MOVE_LEFT
}
public class SpaghettiAct : MonoBehaviour
{
[SerializeField] private GameObject player1;
[SerializeField] private GameObject player2;
private MOVE move = MOVE.MOVE_RIGHT;
private void Start()
{
StartCoroutine("MixedAct");
}
IEnumerator MixedAct()
{
while (true)
{
player1.transform.Rotate(90.0f * Vector3.up);
player2.transform.Rotate(90.0f * Vector3.up);
if(player1.transform.position.x < -4)
{
move = MOVE.MOVE_RIGHT;
}
else if(player1.transform.position.x > 4)
{
move = MOVE.MOVE_LEFT;
}
if(move == MOVE.MOVE_RIGHT)
{
player1.transform.Translate(1.0f * Vector3.right, Space.World);
player2.transform.Translate(-1.0f * Vector3.right, Space.World);
}
else
{
player1.transform.Translate(-1.0f * Vector3.right, Space.World);
player2.transform.Translate(1.0f * Vector3.right, Space.World);
}
yield return new WaitForSeconds(0.5f);
}
}
}
//Component ํจํด์ ์ ์ฉํด์ ํด๋์ค๋ฅผ ๋ถ๋ฆฌํ์ฌ ์์ฑํ์ ๋
using System.Collections;
using UnityEngine;
public class RotateAct : MonoBehaviour
{
private void Start()
{
StartCoroutine("Rotate");
}
IEnumerator Rotate()
{
while (true)
{
transform.Rotate(90.0f * Vector3.up);
yield return new WaitForSeconds(0.3f);
}
}
}
using System.Collections;
using UnityEngine;
enum MOVE
{
MOVE_RIGHT,
MOVE_LEFT
}
public class MoveAct : MonoBehaviour
{
private MOVE move = MOVE.MOVE_RIGHT;
private void Start()
{
StartCoroutine("Move");
}
IEnumerator Move()
{
while (true)
{
if(transform.position.x < -4)
{
move = MOVE.MOVE_RIGHT;
}
else if(transform.position.x > 4)
{
move = MOVE.MOVE_LEFT;
}
if(move == MOVE.MOVE_RIGHT)
{
transform.Translate(1.0f * Vector3.right, Space.World);
}
else
{
transform.Translate(-1.0f * Vector3.right, Space.World);
}
yield return new WaitForSeconds(0.5f);
}
}
}
ํ์ ํ๋ ๊ฐ์ฒด์ ์ด๋ํ๋ ๊ฐ์ฒด์ ๋ถ์ผ ์คํฌ๋ฆฝํธ๋ฅผ ๋ถ๋ฆฌํ์๋ค.
๊ฐ๋ ์ฑ, ์ ์ง๋ณด์๋ฅผ ์ํด์๋ผ๋ Component ํจํด์ ์ ์ฉํด์ผ ํ๋ค.
'๐ Computer Science > Design Pattern' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Unity][๋์์ธ ํจํด] Simple Factory Pattern(์ฌํ ํฉํ ๋ฆฌ ํจํด) (0) | 2023.09.13 |
---|---|
[C#][Unity][๋์์ธ ํจํด] Strategy Pattern(์ ๋ต ํจํด) (0) | 2023.09.05 |
[C#][Unity][๋์์ธ ํจํด] Command ํจํด (0) | 2023.09.05 |
[Unity][๋์์ธ ํจํด] Observer Pattern (0) | 2023.09.03 |