C# · Programming

Getting command line arguments in a Unity executable

In my last blog post, I wrote about how to set the VR run mode of an executable. I mentioned using command line arguments and detecting them inside Unity. I didn’t get into how you actually detect command line args because it turned out they weren’t really needed to accomplish what I was blogging about, but they’re really really useful to have in the toolbox, so I thought I’d follow up with this quick post.

Example uses for command line args might be launching a game in debug mode, enabling cheats or turning a particular feature on or off – great for testing. You can have as many different arguments as you want, too, so mixing and matching configuration options is a thing, too.

Launching an executable with command line arguments

To launch an executable file with command line arguments in Windows, you need to set up a shortcut (right click on the executable, then choose create shortcut from the menu). You then right click on the shortcut, choose Properties. Move to the Shortcut tab and you can then edit the Target field. In the Target field, you add the arguments after the path to the exe, like this:

In the shortcut above, the argument -cheatsEnabled .. you can guess what this might do. If you wanted to add some more arguments, you can separate them with spaces.

Reading command line arguments in Unity

Unity provides us with the function GetCommandLineArgs() to get at any incoming arguments. It will return an array of strings we can then loop through and check against. Here’s an example of reading the command line arguments and looking for -disableVR, -cheatsEnabled or -debugMode arguments:

        string[] args = System.Environment.GetCommandLineArgs();
        for (int i = 0; i < args.Length; i++)
        {
            if (args[i].Contains("-disableVR"))
            {
                GameProperties.VREnabled = false;
            } 
            else if (args[i].Contains("-cheatsEnabled"))
			{
                GameProperties.CheatsEnabled = true;
            }
            else if (args[i].Contains("-debugMode"))
            {
                GameProperties.DebugMode = true;
            }
        }

That’s about it, really. Grab the string[] array with System.Environment.GetCommandLineArgs() and iterate through it to read each parameter.

Have fun!