본문 바로가기
Unity3D/Unity & C#

Unity & C# ~ 두 오브젝트의 색상과 이미지가 중복되지 않는 랜덤 출력

by 캬캬백곰 2022. 10. 7.
728x90
using System.Collections;
using System.Collections.Generic;

using UnityEngine;
using UnityEngine.UI;

public class TestRandomObjectsColor : MonoBehaviour
{
    [SerializeField] List<Color> RanColors;     // 사용될 색상
    [SerializeField] List<Image> RanObjects;    // 1번 이미지에 사용될 이미지들
    [SerializeField] List<Image> RanObjects1;   // 2번 이미지에 사용될 이미지들

    private Coroutine RanCoroutine = null;

    private int ColorValue { get; set; }        // 1번 이미지 색상 값
    private int PrevColorValue { get; set; }    // 1번 이미지 이전 색상 값
    private int ColorValue1 { get; set; }       // 2번 이미지 색상 값
    private int PrevColorValue1 { get; set; }   // 2번 이미지 이전 색상 값
    private int ObjectValue { get; set; }       // 1번 이미지에 사용할 이미지 번호
    private int PrevObjectValue { get; set; }   // 1번 이미지에 사용된 이전 이미지 번호
    private int ObjectValue1 { get; set; }      // 2번 이미지에 사용할 이미지 번호
    private int PrevObjectValue1 { get; set; }  // 2번 이미지에 사용된 이전 이미지 번호

    private void OnEnable()
    {
        RanCoroutine = StartCoroutine(RanChangeCoroutine());
    }

    IEnumerator RanChangeCoroutine()
    {
        //이전 값 저장
        PrevColorValue = ColorValue;
        PrevColorValue1 = ColorValue1;
        PrevObjectValue = ObjectValue;
        PrevObjectValue1 = ObjectValue1;

        do
        {
            ColorValue = UnityEngine.Random.Range(0, RanColors.Count);      // 1번 이미지 색상 랜덤 값
            ColorValue1 = UnityEngine.Random.Range(0, RanColors.Count);     // 2번 이미지 색상 랜덤 값
            ObjectValue = UnityEngine.Random.Range(0, RanObjects.Count);    // 1번 이미지에 사용할 이미지 번호
            ObjectValue1 = UnityEngine.Random.Range(0, RanObjects.Count);   // 2번 이미지에 사용할 이미지 번호
        }
        while ((ColorValue == PrevColorValue || ObjectValue == PrevObjectValue)         // 1번 이미지의 이미지와 색상이 이전 값과 다르거나
                || (ColorValue1 == PrevColorValue1 || ObjectValue1 == PrevObjectValue1) // 2번 이미지의 이미지와 색상이 이전 값과 다르거나
                || (ColorValue == ColorValue1 || ObjectValue == ObjectValue1));         // 1번 이미지와 2번 이미지의 색상과 사용될 이미지가 다르면

        for (int i = 0; i < RanObjects.Count; i++)
        {
            RanObjects[i].gameObject.SetActive(i == ObjectValue);
        }

        for (int i = 0; i < RanObjects1.Count; i++)
        {
            RanObjects1[i].gameObject.SetActive(i == ObjectValue1);
        }

        RanObjects[ObjectValue].color = RanColors[ColorValue];
        RanObjects1[ObjectValue1].color = RanColors[ColorValue1];

        yield return new WaitForSeconds(1);

        RanCoroutine = StartCoroutine(RanChangeCoroutine());
    }

    private void OnDisable()
    {
        StopAllCoroutines();
    }
}

 

 

최종 결과

 

728x90
반응형