下のような感じでリスト作ってるんですがググってもうまい具合にシャッフルの機能を実装できず困っています。
助言お願いします。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class cardGenerator : MonoBehaviour
{
public GameObject cardPrefab;//インスタンス化のための
public GameObject hand;//親にする要素指定
List<cardData> cardDataList = new List<cardData>() { new cardData(10,"ヤドラン","水鉄砲"), new cardData(1,"か","日"), new cardData(1,"1","1"), new cardData(1,"2","3"), }; void Start() { { for (int i = 0; i < cardDataList.Count; i++) { GameObject cardObj = Instantiate(cardPrefab);//生産 cardObj.transform.SetParent(hand.transform);//親指定 Card card = cardObj.GetComponent<Card>();//カードクラスのカード変数にスクリプト代入 Debug.Log(card == null); card.Load(cardDataList[i]); } } } private void Update() { if (Input.GetKeyDown(KeyCode.LeftShift)) { GameObject cardObj = Instantiate(cardPrefab);//生産 cardObj.transform.SetParent(hand.transform);//親指定 Card card = cardObj.GetComponent<Card>();//カードクラスのカード変数にスクリプト代入 Debug.Log(card == null); card.Load(cardDataList[0]); cardDataList.RemoveRange( 0, 1); if (Input.GetKeyDown(KeyCode.Space)) { Shuffle(cardDataList); } } } //リストの要素をシャッフルする (Fisher-Yates shuffle) public static void Shuffle<T>(List<T> list) { for (int i = list.Count - 1; i > 0; i--) { int j = Random.Range(0, i + 1); //[0]~[i] Swap(list, i, j); } } public static void Swap<T>(List<T> list, int i, int j) { T tmp = list[i]; list[i] = list[j]; list[j] = tmp; }
}
回答2件
あなたの回答
tips
プレビュー