unity3d 设置活动随机对象Unity 2d

z31licg0  于 2023-01-09  发布在  其他
关注(0)|答案(1)|浏览(136)

我想在步骤脚本中随机设置活动1索引。计数= 2,随机将继续显示,但它不工作。
我的代码:

public class Step 
{
    public string stepName;
    public GameObject[] objects;
}
public void AddCount()
    {
        Count++;
        if (Count == 2)
        {
            nextStep();
            Count = 0;
        }
        
    }
    public void nextStep()
    {

        for (int i = 0; i < _steps.Count; i++)
        {
            int ranI = Random.Range(0, _steps.Count - 1);

            _steps[ranI].objects[i].SetActive(true);

        }
    }

谢啦,谢啦

k75qkfdt

k75qkfdt1#

您是否确定每个步骤包含的对象数至少与_steps列表本身中的步骤数一样多...?
访问

_steps[ranI].objects[i]

在我看来毫无意义。
听起来您更希望选择一个随机步骤,然后启用所有相应的对象。
为了也禁用当前步骤,我将保留该信息,例如

// Stores which step is currently being displayed so we can hide it later
private int? currentStepIndex;

public void nextStep()
{
    // if there is currently a step displayed 
    if(currentStepIndex != null)
    {
        // hide all that step's objects
        var step = _steps[currentStepIndex];

        foreach(var obj in step.objects)
        {
            obj.SetActive(false);
        }
    }

    // pick a random step
    // Note that the upper index already is exclusive
    // => this will return valid indices between 0 and _steps.Count - 1 now
    currentStepIndex = Random.Range(0, _steps.Count);
    var nextStep = _steps[currentStepIndex];

    // enable all that step's objects
    foreach(var obj in nextStep.objects)
    {
        obj.SetActive(true);
    }
}

我个人甚至会将循环抽象为Step类本身

public class Step 
{
    public string stepName;
    // This can be private now
    [SerializeField] private GameObject[] objects;

    public void SetActive(bool active)
    {
        foreach(var obj in objects)
        {
            obj.SetActive(active);
        }
    }
}

而是存储Step并执行

private Step currentStep;

public void nextStep()
{
    currentStep?.SetActive(false);

    var currentStepIndex = Random.Range(0, _steps.Count);
    currentStep = _steps[currentStepIndex];

    currentStep.SetActive(true);
}

因为通过这种方式,您还可以排除当前步骤,这样您就不会在一行中随机选取相同的索引两次。或者甚至确保每个步骤只选取一次,直到所有步骤都显示出来,等等

相关问题