首页 > 解决方案 > 为什么我的代码不能在 Unity 中运行?统一 C#

问题描述

出于某种原因,我的代码无法正常工作......我不知道为什么。有人可以帮忙吗?我正在使用 switch 语句来控制我的代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour {

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        Vector3 pos = transform.position;
        string state = "idle";
        float vx = 0f;
        float vy = 0f;
        float playerSpeed = 2f * Time.deltaTime;

        switch (state) {
            case "idle": 
                vx = 0;
                vy = 0;

                if (Input.GetKey (KeyCode.A)) state = "left";
                if (Input.GetKey (KeyCode.D)) state = "right";
                if (!Input.GetKey (KeyCode.D) && !Input.GetKey (KeyCode.A)) state = "idle";             
                break;

            case "left":
                vx = -1 * playerSpeed;
                vy = 0;

                if (Input.GetKey (KeyCode.A)) state = "left";
                if (Input.GetKey (KeyCode.D)) state = "right";
                if (!Input.GetKey (KeyCode.D) && !Input.GetKey (KeyCode.A)) state = "idle";             
                break;

            case "right":
                vx = playerSpeed;
                vy = 0;

                if (Input.GetKey (KeyCode.A)) state = "left";
                if (Input.GetKey (KeyCode.D)) state = "right";
                if (!Input.GetKey (KeyCode.D) && !Input.GetKey (KeyCode.A)) state = "idle";             
                break;
        }
        vx += pos.x;
        vy += pos.y;
        pos += transform.position;

    }
}

控制台没有错误,我的代码看不到任何错误......

请帮忙!

非常感谢任何答案。

谢谢。

标签: c#unity3dscripting

解决方案


您正在评估每个 switch 案例中的输入,而不是在评估 switch 之前。您还在检查输入,然后检查是否缺少输入,因此只需用于else清理这些检查。你也什么都不做,vy = 0所以不要费心设置:

if (Input.GetKey (KeyCode.A))
    state = "left";
else if (Input.GetKey (KeyCode.D)) // if you hold both A and D, A will get priority
    state = "right";
else
    state = "idle";
switch(state)
{
    case("idle")
        vx = 0;
        break;
    case("left")
        vx = playerSpeed;
        break;
    case("right")
        vx = -1 * playerSpeed;
        break;
}

您也没有正确地将值添加到转换的位置,您只是将它们添加到您的临时变量中,pos(您根本不需要的变量):

vx += pos.x;
vy += pos.y;
pos += transform.position;

应该改为:

transform.position.Translate(vx, vy, 0);

我还想指出,开关本身完全没有意义,但我把这个作为我的答案,所以很清楚做错了什么;你应该只是在 // 语句中设置你的vx值。ifelse ifelse


推荐阅读