using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Keyboard_Input : MonoBehaviour {
public float speed = 5f;
void Start () {
Dictionary<KeyCode, Vector3> directions = new Dictionary<KeyCode, Vector3>();
{
directions.Add(KeyCode.W, Vector3.forward );
directions.Add(KeyCode.S, Vector3.back );
directions.Add(KeyCode.A, Vector3.left );
directions.Add(KeyCode.D, Vector3.right );
};
}
void Update () {
foreach(KeyValuePair<KeyCode, Vector3> direction in directions)
{
if (Input.GetKey(directions))
{
this.transform.Translate(directions[direction] * speed * Time.deltaTime, Space.Self);
}
}
}
}
1.我每次写指示时都会收到错误 - 当前上下文中不存在“方向”这个名称 这发生在第25,27,30行
答案 0 :(得分:3)
您在directions
方法中声明Start
,因此它是一个本地变量。您应该将其声明为字段 - 并且我将其设置为静态字段,因为您不需要为每个实例使用不同的字典。您可以使用集合初始值设定项在一个表达式中初始化它:
private static readonly Dictionary<KeyCode, Vector3> directions =
new Dictionary<KeyCode, Vector3>
{
{ KeyCode.W, Vector3.forward },
{ KeyCode.S, Vector3.back },
{ KeyCode.A, Vector3.left },
{ KeyCode.D, Vector3.right }
};
答案 1 :(得分:-1)
你使用{};在字典初始化中你不应该这样做。
void Start ()
{
Dictionary<KeyCode, Vector3> directions = new Dictionary<KeyCode, Vector3>();
directions.Add(KeyCode.W, Vector3.forward );
directions.Add(KeyCode.S, Vector3.back );
directions.Add(KeyCode.A, Vector3.left );
directions.Add(KeyCode.D, Vector3.right );
}
或者您可以使用集合初始化程序初始化它:
void Start ()
{
var directions = new Dictionary<KeyCode, Vector3>
{
{ KeyCode.W, Vector3.forward },
{ KeyCode.S, Vector3.back },
{ KeyCode.A, Vector3.left },
{ KeyCode.D, Vector3.right}
};
}