【问题标题】:Curly braces not working like they should in c# unity花括号在 c# unity中不能正常工作
【发布时间】:2019-04-22 11:31:44
【问题描述】:

我正在制作一个统一游戏,然后我脚本中的花括号变得愚蠢。他们都搞砸了,我不知道我做错了什么。这是我的脚本: ps:我用的是visual studio

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

public class MoveSript : MonoBehaviour {
    public GameObject myObject;
    // Use this for initialization
    private Vector3 direction = new Vector3(0, 0, 0);
    // Update is called once per frame
    private float speed = 40f;
    void Start() { // error here? --> "} expected"

        private Camera cam = Camera.main;
        private float height = 2f * cam.orthographicSize;
        private float width = height * cam.aspect;
    } // i close it here, but it closes the mono beh. class instead?

    void Update () {
        int y = 0;
        int x = 0;
        if (Input.GetKey("up"))
        {
            y = 1;
        }
        if (Input.GetKey("down"))
        {
            y = -1;
        }
        if (Input.GetKey("right"))
        {
            x = 1;
        }
        if (Input.GetKey("left"))
        {
            x = -1;
        }
        direction = new Vector3(x, y, 0);
        myObject.transform.position += direction.normalized*speed*Time.deltaTime;
    }
}

我做错了什么?感谢您的提前!

【问题讨论】:

  • 是否出现任何错误?你的意思是缩进搞砸了?
  • @fhcimolin 我在 Visual Studio 中执行此操作,在“start() {”处显示“}预期”,但我稍后将其关闭?
  • 你在一个实例方法中声明全局变量,检查你的start方法,private不能在那里使用。
  • private 关键字不属于(或有意义)方法中的本地声明变量。尽量少关注对编译器的侮辱性名称,多关注代码的语法和结构。我向你保证,你不会伤​​害编译器的感受或让它改变主意。
  • 啊,好的,谢谢。我对 c# 还很陌生,所以我忘记了 private 是做什么的,但使用它 lol

标签: c# unity3d


【解决方案1】:

您不能在方法内定义的局部变量中定义可访问性。它应该是

private void Start() 
{
    var cam = Camera.main;
    var height = 2f * cam.orthographicSize;
    var width = height * cam.aspect;

    // Makes only sense if you now use the width
    // and/or other values for something
}

或者在类级别定义它们(例如,以后也可以在其他方法中访问它们),例如

private Camera cam;
private float height;
private float width;

private void Start() 
{
    cam = Camera.main;
    height = 2f * cam.orthographicSize;
    width = height * cam.aspect;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-14
    • 1970-01-01
    • 2013-08-07
    • 2015-03-24
    • 1970-01-01
    • 1970-01-01
    • 2021-01-11
    • 2018-05-02
    相关资源
    最近更新 更多