大括号无法正常工作,在C#中

时间:2019-04-22 11:31:44

标签: c# unity3d

我当时正在做一个统一的游戏,然后我剧本中的花括号变得哑了。他们都搞砸了,我不知道我在做什么错。这是我的脚本: 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;
    }
}

我在做什么错?感谢您的进步!

2 个答案:

答案 0 :(得分:2)

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

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;
}

答案 1 :(得分:-1)

感谢大家对我说的话,问题出在声明start()中的变量时出现在private语句中。我应该让它们浮起来 因此,Start()的外观是:

void Start() { // error here? --> "} expected"
        Camera cam = Camera.main; // delete private
        float height = 2f * cam.orthographicSize; // also here
        float width = height * cam.aspect; // also here
    } // i close it here, but it closes the mono beh. class instead?