Dictionary function for Character Contoller

    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.So I get an error for each time i write directions- The name 'directions' does not exist in the current context This happens on lines 25,27,30

Thankyou In Advance

Jon Skeet
people
quotationmark

You're declaring directions within the Start method, so it's a local variable. You should declare it as a field - and I'd make it a static field, as you don't need a different dictionary for each instance. You can use a collection initializer to initialize it all in one expression:

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

people

See more on this question at Stackoverflow