我试图做一个图片游戏测验-游戏的核心机制是从4个选择中选择正确的图片以匹配给定的单词。我一直在尝试使用数组/列表将图片与单词配对。但不知道如何。需要一个英雄来帮助我!我对团结非常陌生,所以我只需要一个指南:)
public class listtest : MonoBehaviour
{
public List<GameObject> vp = new List<GameObject>();
public List<string> word = new List<string>();
}
最终结果可能至少应该显示配对。
答案 0 :(得分:3)
假设您的列表排列正确,并且大小完全相同
public Dictionary<string, GameObject> ImageByString = new Dictionary<string, GameObject>();
public Dictionary<GameObject, string> StringByImage = new Dictionary<GameObject, string>();
private void Start()
{
// at least have an "emergency" check and use the smaller list count
var count = Mathf.Min(vp.Count, word.Count);
for(var i = 0; i < count; i++)
{
ImageByString.Add(word[i], vp[i]);
StringByImage.Add(vp[i], word[i]);
}
}
或使用Linq
using System.Linq;
...
private void Start()
{
ImageByString = word.Zip(vp, (k, v) => new {k, v}).ToDictionary(x => x.k, x => x.v);
StringByImage = vp.Zip(word, (k, v) => new {k, v}).ToDictionary(x => x.k, x => x.v);
}
但是,这不会显示在Unity Inspector中。如果您要实现这一目标,则应该实现自己的类,例如
[Serializable]
public class WordImagePair
{
public string word;
public GameObject vp;
}
然后,您必须“相信”所有word
值都是唯一的,因此您可以轻松做到
public List<WordImagePair> pairs = new List<WordImagePair>();
现在要么再次使用字典,如
public Dictionary<string, GameObject> ImageByString = new Dictionary<string, GameObject>();
public Dictionary<GameObject, string> StringByImage = new Dictionary<GameObject, string>();
private void Start()
{
foreach(var pair in pairs)
{
ImageByString.Add(pair.word, pair.vp);
StringByImage.Add(pair.vp, pair.word);
}
}
或再次与Linq
private void Start()
{
ImageByString = pairs.ToDictionary(p => p.word, p => p.vp);
StringByImage = pairs.ToDictionary(p => p.vp, P => p.word);
}
或稍后直接使用Linq来访问图像,例如
public GameObject ImageByString(string word)
{
var output = pairs.FirstOrDefault(p => string.Equals(p.word, word));
if(output == null)
{
Debug.LogErrorFormat(this, "No Image with word=\"{0}\" found!", word);
}
return output;
}
public string StringByImage(GameObject vp)
{
var output = pairs.FirstOrDefault(p => p.vp == vp);
if(output == null)
{
Debug.LogErrorFormat(this, "No word for given GameObject {0} found!", vp.name);
}
return output;
}
注意:请在智能手机上输入内容,因此没有保修,但我希望这个想法会清楚。