Var在当前上下文中不存在

时间:2017-10-04 14:24:18

标签: c# unity3d

我正在做" PlayerMoveKeyBoard"使用Unity,我使用了这段代码:

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

public class MovingScript : MonoBehaviour {

    // Use this for initialization
    void Start () {
        double x;
        double y;
        double z;
        double speed;
    }

    // Update is called once per frame
    void Update () {
        speed = speed * 0.95;
        if (Input.GetKeyDown("Up")) {
            speed += 2;
            transform.Translate (speed, 0, 0);
        }
        if (Input.GetKeyDown("Down")) {
            speed += 2;
            transform.Translate (-speed, 0, 0);
        }
        if (Input.GetKeyDown("Right")) {
            speed += 2;
            transform.Translate (0, 0, speed);
        }
        if (Input.GetKeyDown("Left")) {
            speed += 2;
            transform.Translate (0, 0, -speed);
        }
    }
}

但它说:

  

(17,11)名称'速度'在当前上下文中不存在

3 个答案:

答案 0 :(得分:2)

您已在方法Start范围内本地声明了变量:

void Start () {
    double x;
    double y;
    double z;
    double speed;
}

在此方法之外,无法访问这些变量。您需要在类级别声明它们:

public class MovingScript : MonoBehaviour {

    double x;
    double y;
    double z;
    double speed;

    // Update is called once per frame
    void Update () {
        speed = speed * 0.95;
        if (Input.GetKeyDown("Up")) {
            speed += 2;
            transform.Translate (speed, 0, 0);
        }
        if (Input.GetKeyDown("Down")) {
            speed += 2;
            transform.Translate (-speed, 0, 0);
        }
        if (Input.GetKeyDown("Right")) {
            speed += 2;
            transform.Translate (0, 0, speed);
        }
        if (Input.GetKeyDown("Left")) {
            speed += 2;
            transform.Translate (0, 0, -speed);
        }
    }
}

请阅读Variables and Method Scope in this article

答案 1 :(得分:1)

您在名为局部变量的方法中声明的所有变量,只能在该方法中访问。这里没有在Update方法中声明速度,因此你无法访问它。一旦你离开Start方法的范围,它就会在Start方法中声明它消失了。要在Update方法中访问它,您需要在Update方法中声明它。

像这样:

 void Update()
    {
        float speed = 0.0f;
        speed = speed * 0.95;
        if (Input.GetKeyDown("Up"))
        {
            speed += 2;
            transform.Translate(speed, 0, 0);
        }
        if (Input.GetKeyDown("Down"))
        {
            speed += 2;
            transform.Translate(-speed, 0, 0);
        }
        if (Input.GetKeyDown("Right"))
        {
            speed += 2;
            transform.Translate(0, 0, speed);
        }
        if (Input.GetKeyDown("Left"))
        {
            speed += 2;
            transform.Translate(0, 0, -speed);
        }
    }
}

答案 2 :(得分:0)

你需要在开始之外,在类本身中声明速度。

    public class MovingScript : MonoBehaviour {

    double speed;

    // Use this for initialization
    void Start () {
        double x;
        double y;
        double z;

    }