本文介绍了Unity C#在被选中后从列表中随机打印字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
I have two lists with 4 strings each. I shuffle them and then I select a string on each list to create a combination of strings from both lists. I want the four combinations (written below) repeated four times (so 16 combinations in total) but each of these combination should be presented in a random order.
Dog
Lion
Dog and car
Lion and car
From this code, I shuffle the strings then I select the first string from each list, I iterate using for loops and then generate 16 combinations. This code can shuffle, select and the prints are totally fine BUT prints the first selected string - 4 times, then the second selected string - 4 times. So everything works fine except that the order isn't random. So if dog is selected from the first list, it will print: dog, dog and car, dog, dog and car, then it will do this for lion (for the next 4 prints). So it will always print 4 times the string that gets selected from the first list. Whereas I want those selection to be random. Any advice would be helpful.
我的尝试:
What I have tried:
<pre>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.UI;
using System;
using System.Linq;
public class randomLetters : MonoBehaviour
{
List<string> mylist = new List<string>();
List<string> mylist2 = new List<string>();
string selected;
string selected2;
void Start()
{
mylist.Add("dog");
mylist.Add("lion");
mylist.Add("dog");
mylist.Add("lion");
mylist2.Add("carfordog");
mylist2.Add("carforlion");
mylist2.Add("carfordog");
mylist2.Add("carforlion");
Shuffle(mylist);
Shuffle(mylist2);
StartCoroutine(Wait());
}
IEnumerator Wait()
{
for (int i = 0; i < 4; i++)
{
selected = mylist[i];
for (int j = 0; j < 4; j++)
{
selected2 = mylist2[j];
if (selected == "dog" && selected2 == "carfordog")
{
Debug.Log("Dog and Car");
}
else if (selected == "dog" && selected2 == "carforlion")
{
Debug.Log("Dog ");
}
else if (selected == "lion" && selected2 == "carforlion")
{
Debug.Log("Lion and Car ");
}
else if (selected == "lion" && selected2 == "carfordog")
{
Debug.Log("Lion");
}
yield return new WaitForSeconds(1);
}
yield return new WaitForSeconds(1);
}
}
void Shuffle(List<string> lists)
{
for (int j = lists.Count - 1; j > 0; j--)
{
int rnd = UnityEngine.Random.Range(0, j + 1);
string temp = lists[j];
lists[j] = lists[rnd];
lists[rnd] = temp;
}
}
}
推荐答案
这篇关于Unity C#在被选中后从列表中随机打印字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!