c# - 变量设置行会干扰顶级语句

标签 c# unity-game-engine

我不知道这个脚本有什么问题。我尝试将所有变量放入“void Start()”中,但没有任何效果。请帮忙。 据我所知,更新脚本中的所有内容都不是问题。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MovementScript : MonoBehaviour{ }

{
    Rigidbody PlayerCube;
    float Jump = 1;
    float Speed = 1;
    void Update()
    {
        // All of this has the controls tilted 45 degrees. Deal with it for now.
        if (Input.GetKey(KeyCode.W)) ;
        { PlayerCube.AddForce(0, 0, Speed * 5); }

        if (Input.GetKey(KeyCode.S)) ;
        { PlayerCube.AddForce(0, 0, Speed * -5); }

        if (Input.GetKey(KeyCode.A)) ;
        { PlayerCube.AddForce(Speed * 5, 0, 0); }

        if (Input.GetKey(KeyCode.D)) ;
        { PlayerCube.AddForce(Speed * -5, 0, 0); }

        if (Input.GetKeyDown(KeyCode.Space)) ;
        { PlayerCube.AddForce(0, (float)(Jump * 2.5), 0); }
    }
}

最佳答案

  • 删除MonoBehaviour后面的一对括号{ }
  • 删除每个 if 语句后的分号 ;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MovementScript : MonoBehaviour
{
    Rigidbody PlayerCube;
    float Jump = 1;
    float Speed = 1;

    void Update()
    {
        // All of this has the controls tilted 45 degrees. Deal with it for now.
        if (Input.GetKey(KeyCode.W))
        { PlayerCube.AddForce(0, 0, Speed * 5); }

        if (Input.GetKey(KeyCode.S))
        { PlayerCube.AddForce(0, 0, Speed * -5); }

        if (Input.GetKey(KeyCode.A))
        { PlayerCube.AddForce(Speed * 5, 0, 0); }

        if (Input.GetKey(KeyCode.D))
        { PlayerCube.AddForce(Speed * -5, 0, 0); }

        if (Input.GetKeyDown(KeyCode.Space))
        { PlayerCube.AddForce(0, (float)(Jump * 2.5), 0); }
    }
}

为了简单起见,修改您的 Update() 方法

void Update()
{
    PlayerCube.AddForce(-Speed * 5 * Input.GetAxisRaw("Vertical"), 0, Speed * 5 * Input.GetAxisRaw("Horizontal"));

    if (Input.GetKeyDown(KeyCode.Space))
    {
        PlayerCube.AddForce(0, (float)(Jump * 2.5), 0);
    }
}

关于c# - 变量设置行会干扰顶级语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73242442/

相关文章:

ios - 如何从 Unity 或 Xcode 更改最近的 iOS 应用程序图标

ios - 在 Unity 中接收来自客户端的消息

c# - Unity 中游戏对象的水平重力

c# - GAE 上的 RoR?

c# - LINQ 表达式返回属性值?

c# - 是否有适用于 .Net 3.5 的 C#4.0 更改列表?

ios - 如何防止 Firebase Cloud Messaging 在 iOS/Unity 上请求推送通知权限

c# - 不使用 SqlParameterCollection 时,SqlParameter 已包含在另一个 SqlParameterCollection 中

c# - .net(C#) 比较两个字符串列表并删除不匹配的元素

unity-game-engine - 如何将 MonoBehaviour 移动到外部程序集并且不卡在 "Missing (mono script)"中?