Фигурные скобки не работают, как они должны в C # Unity - PullRequest
0 голосов
/ 22 апреля 2019

я делал игру на единство, затем мои фигурные скобки в моем сценарии стали тупыми. Они все испортили, и я не знаю, что я делаю неправильно. Вот мой сценарий: 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;
    }
}

Что я делаю не так? Спасибо за продвижение!

1 Ответ

2 голосов
/ 22 апреля 2019

Вы не можете определить доступность в локальных переменных, определенных внутри метода. Это должно быть либо

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;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...