unity3d 我可以让同一个元素在列表中重复多次吗?

brjng4g3  于 2022-11-16  发布在  其他
关注(0)|答案(1)|浏览(221)

我是一个Unity开发者,我有一个AI角色可用的空闲状态列表。目前我正在通过我的检查器中的公共列表控制执行顺序,它工作正常,然而,当我尝试按照执行顺序第二次执行同一元素时,我的列表会卡在重复元素和循环中的下一个元素之间,无法运行我的元素中。
我应该张贴我的名单脚本?再次感谢各位。

public class Idle : MonoBehaviour
{
public enum IdleState
{
    BasicIdle,
    PlayingWithKids,
    Playfull,
    Curious,
    Bored,
    MoveToCamera,
    Waiting,
    PlantMode,
    Shy,
    Crying
}

public List<IdleState> availableIdleStates = new List<IdleState>()
{
    IdleState.BasicIdle,
    IdleState.PlayingWithKids,
    IdleState.Playfull,
    IdleState.Curious,
    IdleState.Bored,
    IdleState.Waiting,
    IdleState.PlantMode,
    IdleState.Shy,
    IdleState.Crying
};

private void FixedUpdate()
{
    if (Time.timeSinceLevelLoad > prevIdleStateChangeTime + currentStateDuration)
    {
        int i = availableIdleStates.FindIndex(x => x.Equals(currentIdleState))+1;
        //i %= availableIdleStates.Count;
        if (i >= availableIdleStates.Count)
        {
            i = 0;
            //TODO: Shuffle available states list 
        }
        changeState(availableIdleStates[i]);
    }
    switch (currentIdleState)
    {
        case IdleState.BasicIdle:
            if (Time.timeSinceLevelLoad > subStateChangeTime + subStateDuration)
            {
                subStateDuration = Random.Range(20f, 30f);
                Debug.Log(subStateDuration);
                int randInt = Random.Range(0, 1);
                subStateChangeTime = Time.timeSinceLevelLoad;
                switch (randInt)
                {
                    case 0:
                        CurrentMovingState = Moving.MovingState.MoveAndRotateToTarget;
                        return;
                    case 1:

                       CurrentMovingState = Moving.MovingState.MoveAndRotateToTarget;
                        return;
                    //case 2:

                    //   CurrentMovingState = Moving.MovingState.MoveAndRotateToTargetWithRotation;
                    //    return;
                }
            }
            return;

这种方法被称为每次状态更改

private void changeState(IdleState NewState)
{
    currentIdleState = NewState;
    prevIdleStateChangeTime = Time.timeSinceLevelLoad;
    subStateChangeTime = Time.timeSinceLevelLoad;
    subStateDuration = -1;
 }
62lalag4

62lalag41#

private enum states
{
    state1,
    state2
}

private states current;

private void stateChanged()
{
    switch (current)
    {
        case states.state1:

            break;

        case states.state2:

            break;

        default:

            break;
    }
}

上面的代码示例显示了如何使用枚举和switch case语句来根据当前状态执行特定代码,因此,您应该首先设置当前状态current = states.state1;,然后调用将执行正确代码的stateChanged方法。
如果您只想让程序按照设置顺序循环所有状态,例如从状态1到状态2,您也不需要所有状态的列表,只需在达到某个时间限制后设置当前current = (states)(int)current + 1;即可。

相关问题