- Home /
Is there a way to replay input on a gameobject?
For example, I'd like to move my object with my controls and if I hold down w then it records that key press and for how long it was held down, and then stores this information somewhere. Then later using that information I can replay the same motion on the gameobject (that has physics). Is this something possible to do?
Answer by Habitablaba · Jun 23, 2016 at 05:16 PM
You've described pretty much exactly what you need to do.
Create a new script to add to whatever game object you want to record for. Basically, just listen for all of the relevant key press events (and the associated key release events). When one of them occurs, save the event into a collection -- a list or a dictionary perhaps.
Later, when you want to replay events, you can iterate over the collection and handle those events as if they were being sent from the user.
Edit: You'll also want to look into this answer about simulating key press events. Basically you're going to want a level of indirection between your game and the normal Input.* methods.
Answer by Eno-Khaon · Jun 23, 2016 at 06:42 PM
Getting back information on the key you press can be done using Event.keyCode. To give an example of how the basics of it could be implemented:
// C#
bool[] keyPressed;
int totalKeys;
void Start()
{
KeyCode[] allKeys = (KeyCode[])System.Enum.GetValues(typeof(KeyCode));
totalKeys = allKeys.Length;
keyPressed = new bool[totalKeys];
}
void OnGUI()
{
Event e = Event.current;
// Filtering out the "None" accompanying other keypresses.
if(e.isKey && e.keyCode != KeyCode.None)
{
// Remove repeats while holding key
if(e.type == EventType.KeyDown && !keyPressed[(int)e.keyCode])
{
keyPressed[(int)e.keyCode] = true;
Debug.Log((int)e.keyCode + " --- " + e.keyCode + " --- down");
}
else if(e.type == EventType.keyUp)
{
keyPressed[(int)e.keyCode] = false;
Debug.Log((int)e.keyCode + " --- " + e.keyCode + " --- up");
}
}
}
Woah, wait a second! Isn't that boolean array too big? There aren't that many KeyCodes!
Well, there's a lot of empty space in the KeyCode enumerator. In fact, a few hundred "numbers" are skipped.
That simply means we're working around those empty spaces, since the conversion from KeyCode to integer uses the assigned number in the enumerator. It's no easy task to compress the KeyCode inputs into a smaller array.