The other day i was thinking that it could be nice to make an IngameConsole system for my projects and maybe to put in the Asset Store…
I search on the forums but i don´t find any clear reference on how to implement that…
My main question is how do i “read” what I input…
For example if a introdude:
Time.timeScale = 0;
or
camera.fieldOfView = 60;
How do i implement the system that reads that inputs…
I think that these is the harder thing because the set up of the Gui is easy and i suppouse that if i want to add more commands it´s just make new functions … but i dont know!
I don’t think there is an easy way to evaluate real code. However, you could use SendMessage, or parse the input string on your own.
For example, if you input
timeScale set 0
then you would use
string[] code = inputString.Split(" ");
if (code[0] == "timeScale")
{
if (code[1] == "set")
{
Time.timeScale = float.Parse(code[2]);
}
}
To allow the player to affect GameObjects, first allow them to select a GameObject. Then use the “target” keyword in your console (you can use any keyword, or none. It just depends on how you want it to work).
target Camera set fieldOfView 60
Then parse it like this:
string[] code = inputString.Split(" ");
if (code[0] == "target")
{
var component = GetComponent(code[1]);
if (code[2] == "set")
{
var fieldInfo = component.GetType().GetField(code[3]);
fieldInfo.SetValue(component, float.Parse(code[4]));
}
}
This is the simplest console I can think of at the moment. However, it will become more complicated as you add more commands. You just need to determine what features you really want. For example, you could create shorter commands for changing the position, scale, and rotation of GameObjects. You could create commands for common functions (such as setting the camera’s field of view), and leave out reflection-based commands (like the camera example above).
If you choose to use the camera example, note that you will need to check for the FieldInfo’s type (fieldInfo.FieldType) when using SetValue, because you will want to know what kind of data you are dealing with. You don’t want to use float.Parse on a boolean, for example.