一切正常时有条件不起作用

时间:2018-09-13 02:39:29

标签: c# linq unity3d

早上好,我在Unity游戏中有一个脚本,它创建一个列表并将其数字顺序随机化,然后,值传递到另一个列表以检查某些特定属性,这是代码:

// Use this for initialization
private List<int> PreList = new List<int>();
private List<int> ButtonList = new List<int>();
private List<int> UserList = new List<int>();
private System.Random Rnd = new System.Random();

void Randomizer()
{
    PreList.Add(1);
    PreList.Add(2);
    PreList.Add(3);
    PreList.Add(4);
    PreList.Add(5);
    PreList.Add(6);
    PreList.Add(7);
    PreList.Add(8);
    PreList.Add(9);
    PreList = PreList.OrderBy(C => Rnd.Next()).ToList();
    foreach (int Number in PreList)
    { 
        Debug.Log(Number);
        Debug.Log(ButtonList.Count);
        if (Number == 1)
        {
            OneMethod();
        }
        else if (Number == 2)

        {
            TwoMethod();
        }
        else if (Number == 3)

        {
            ThreeMethod();
        }
        else if (Number == 4)

        {
            FourMethod();
        }
        else if (Number == 5)

        {
            FiveMethod();
        }
        else if (Number == 6)

        {
            SixMethod();
        }
        else if (Number == 7)

        {
            SevenMethod();
        }
        else if (Number == 8)

        {
            EightMethod();
        }
        else if (Number == 9)

        {
            NineMethod();
        }
    }
}
    void OneMethod()
    {
        ButtonList.Add(1);
        GameObject RedButton = GameObject.Find("Red"); 
//There are 8 methods just like this, but it variates some stuff like the name and the number, all of these add numbers to ButtonList
    }

此刻,输出控制台仅说ButtonList的计数为9,但是,如果我输入if进行检查,则它永远不会将值设为true,就像它不执行方法和ifs永远不会运行,但是,您对为什么有任何想法吗?

1 个答案:

答案 0 :(得分:1)

我不确定这是否可以解决您的问题,但这是生成随机顺序列表的一种更好的方法:

public class MyClass {
    private List<int> PreList = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    private List<int> ButtonList = new List<int>();
    private List<int> UserList = new List<int>();

    void Randomizer() {
        while (PreList.Count > 0 ) {
            var idx = UnityEngine.Random.Range(0, PreList.Count); // Randomly select from remaining items
            var value = PreList[idx]; // Get item value
            PreList.RemoveAt(idx); // Remove item from future options
            ButtonList.Add(value); // Add to end of 'randomised' list
        }

        foreach (var value in ButtonList) {
            DoSomethingWith(value);
        }
    }

    void DoSomethingWith(int value) {
        switch(value) {
            case 1: OneMethod(); break;
            case 2: TwoMethod(); break;
            case 3: ThreeMethod(); break;
            case 4: FourMethod(); break;
            case 5: FiveMethod(); break;
            case 6: SixMethod(); break;
            case 7: SevenMethod(); break;
            case 8: EightMethod(); break;
            case 9: NineMethod(); break;
        }
    }
}

编辑:添加了DoSomething()

的示例用法