Home > Software engineering >  Unity: allowing keycodes to shift with a variable
Unity: allowing keycodes to shift with a variable

Time:10-10

I'm currently making a purposefully frustrated mini-game where the movement keys change each time you use them. I intended to do this with the code bellow.

public class Flop : MonoBehaviour
{
    private string[] DirF = new string[] { "r","f","v","t","g","b","y","h","u"};
    private string keyF = "y";

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.keyF))
        {
            // insert code to do a little flop and select a new index to represent keyF
        }
    }
}

this is simplified from what I wrote, but essentially using the keyF variable to quickly replace the necessary input in the jump command. Initially I tried to make it a string as shown above, but clearly the KeyCode command doesn't accept strings and I have no idea what variable could be inserted instead.

CodePudding user response:

The Unity KeyCode enum seems like the perfect match for your use case. Instead of storing an array of strings, why not just store an array of KeyCodes? Your code would change to something like:

public class Flop : MonoBehaviour
{
    private KeyCode[] DirF = new KeyCode[] { KeyCode.R, KeyCode.F, KeyCode.V, KeyCode.T, KeyCode.G, KeyCode.B, KeyCode.Y, KeyCode.H, KeyCode.U};

    private KeyCode keyF = KeyCode.Y;

    void Update()
    {
        if (Input.GetKeyDown(keyF)) // We don't need to do KeyCode.keyF since keyF variable is already a KeyCode enumeration option
        {
            (insert code to do a little flop and select a new index to represent keyF)
        }
    }
}

CodePudding user response:

The GetKeyDown method has both KeyCode and string forms for the argument. In your case, you simply need to pass the string representation of the key to the GetKeyDown method, as described here. As such:

public class Flop : MonoBehaviour
{
    private string[] DirF = new string[] { "r","f","v","t","g","b","y","h","u"};
    private string keyF = "y";

    void Update()
    {
        if (Input.GetKeyDown(keyF))
        {
            (insert code to do a little flop and select a new index to represent keyF)
        }
    }
}

The alternative would be to store an array of the KeyCode enums instead.

public class Flop : MonoBehaviour
{
    private KeyCode[] _dirF = new []
    {
        KeyCode.R, 
        KeyCode.F, 
        KeyCode.V, 
        KeyCode.T, 
        KeyCode.G, 
        KeyCode.B, 
        KeyCode.Y, 
        KeyCode.H, 
        KeyCode.U
    };
    private KeyCode _keyF = KeyCode.Y;

    void Update ( )
    {
        if ( Input.GetKeyDown ( _keyF ) )
        {
            // ...
        }
    }
}
  • Related