내일배움캠프/TIL

[내배캠][Unity6기][TIL] 4. 카드 뒤집기(1~4)

binary는 호남선 2024. 9. 9. 19:30

Preview

- Pixels Per Unit
- 바둑판 형태로 배치
- 배열 랜덤으로 정렬하기
- 넘버링된 이미지를 오브젝트에 렌더링하기
- Resources
-- Resources.Load


Pixels Per Unit

- 1개의 Unit(격자 1칸)에 들어가는 픽셀의 개수

- Sprite의 pixel 밀도를 제어

ex) 500x500 픽셀의 이미지를 PPU 500으로 설정하면 1:1 밀도로 1Unit에 전체 이미지가 들어감

바둑판 형태로 배치

- 게임오브젝트를 바둑판 모양으로 배치하는 로직

* 게임오브젝트 Prefab으로 만들어둬야함

public Transform 프리팹이름s;	// 그룹화할 부모 오브젝트(Empty)
public GameObject 프리팹이름;

void Start()
{
    for (int i = 0; i < (행의 개수 * 열의 개수); i++)
    {
        GameObject go = Instantiate(프리팹이름);
        go.transform.parent = 프리팹이름s;

        float x = (i % 열의 개수) * 간격;
        float y = (i / 행의 개수) * 간격;
        go.transform.position = new Vector2(x, y);
    }
}

* 인덱스는 0, 좌하단부터 시작

배열 랜덤으로 정렬하기

[ 0~7의 두개씩 짝지어진 배열 랜덤으로 정렬]

using System.Linq;

int[] arr = { 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7 };
arr = arr.OrderBy(x => Random.Range(0f, 7f)).ToArray();

x => Random.Range(0f, 7f) : 0~7 무작위 float 값을 x에 반환하는 람다식

arr.OrderBy(x => Random.Range(0f, 7f)) : 무작위 값을 기준으로 요소 하나씩 정렬, 기준 값이 랜덤이므로 랜덤하게 정렬됨

arr = arr.OrderBy(x => Random.Range(0f, 7f)).ToArray(); : 형식을 IOrderedEnumerable<int> 에서 배열로 형변환

참고 : https://learn.microsoft.com/ko-kr/dotnet/api/system.linq.enumerable.orderby?view=net-8.0

https://learn.microsoft.com/ko-kr/dotnet/csharp/language-reference/operators/lambda-expressions

넘버링된 이미지를 오브젝트에 렌더링하기

[ 0~7까지 넘버링된 이미지를 0~7까지의 인덱스 가진 오브젝트에 랜더링 ]

/* Board.cs */
void Start()
{
    int[] arr = { 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6 ,7, 7 };

    for (int i = 0; i < 16; i++)
    {
        GameObject go = Instantiate(card, this.transform);
        // arr 인덱스가 0인 카드에 img0이 랜더링됨
        go.GetComponent<Card>().Setting(arr[i]);
    }
}
public class Card : MonoBehaviour
{
    public int index = 0;

    public SpriteRenderer frontImage;

    public void Setting(int idx)
    {
        index = idx;
        // 리소스 폴더의 img{idx} 파일의 Sprite를 frontImage에 랜더
        frontImage.sprite = Resources.Load<Sprite>($"img{idx}");
    }
}

Resources

- 프로젝트에 사용할 리소스를 모아두는 폴더

- Unity 엔진의 코어모듈 中 1, Assets 폴더 아래에 직접 Resources 폴더를 만들어 사용

Resources.Load

public static T Load(string path);
오브젝트 이름.오브젝트 타입 = Resources.Load<가져올 오브젝트 타입>("오브젝트 이름");

- Resources 폴더 내에 있는 오브젝트를 가져오는 함수

- 로드 성공시 가져온 오브젝트를 반환, 로드 실패 시 null 반환

참고 : https://docs.unity3d.com/ScriptReference/Resources.html

https://docs.unity3d.com/ScriptReference/Resources.Load.html