根据单词随机实例化

时间:2019-02-18 19:15:30

标签: c++ arrays unity3d random hashmap

我有一个字=“ CAT” 我有26个字母预制件A-Z-预制件阵列 我想从实例中随机实例化6个预制件 所以B,L,T,C,A,T-以任何随机顺序 但我需要包含组成猫这个词的字母

我的第一个想法是使用字典/哈希图将单词cat映射到数组中的位置,即C = [2] A = [0] T [] 但hashmap / dictionary仅采用一个键值对,但我为它提供了多个需要的3个字母的值

这是统一编程的,所以我的预制件已经在字母数组中,只是让它们包括我的拼写。

public GameObject[] letters;
void Start() {

    int x;

    /* for loop execution */
    for (x = 0; x < 5; x = x + 1)
    {

        CreateCubes();
    }
}

     public void CreateCubes()
    {

        GameObject obj = Instantiate(letters[Random.Range(0, 26)]);
        obj.transform.position = new Vector3(

     );

1 个答案:

答案 0 :(得分:2)

假设所有预制件都位于GameObject[]阵列中,则可以使用它来自动填充字典

public GameObject[] prefabs = new GameObject[26];

private Dictionary<char, GameObject> CharToPrefab = new Dictionary<char, GameObject>(26);

private void Start()
{
    for (var i = 0; i < 27; i++)
    {
        // add 0 to 26 to the start character A
        // results in A-Z
        CharToPrefab[(char)('A' + i)] = prefabs[i];
    }
}

比起您可以通过致电来访问某个预制件

CharToPrefab[character];

要生成实例(最简单的版本,不考虑任何重复),您可以执行例如

public void RandomLetters(string word)
{
    // 1. spawn the minimum required letters to build the word
    foreach (var letter in word)
    {
        var obj = Instantiate(CharToPrefab[letter]);
        // maybe use obj for something e.g. shuffel all instantiated objects positions
    }

    // 2. fill the rest with random letters
    // assuming always same amount as word letters
    var rand = new System.Random();
    foreach (var letter in word)
    {
        // pics a number from 0 to 26
        // and adds it to the char -> results in A-Z
        var randomChar = (char)('A' + rand.Next(0, 27));
        var obj = Instantiate(CharToPrefab[randomChar]);
        // maybe use obj for something e.g. shuffel all instantiated objects positions
    }
}