Skip to content

Instantly share code, notes, and snippets.

@dorktoast
Last active June 16, 2024 10:22
Show Gist options
  • Select an option

  • Save dorktoast/d7c38ba2a54464cea0e0eba7ad0c017f to your computer and use it in GitHub Desktop.

Select an option

Save dorktoast/d7c38ba2a54464cea0e0eba7ad0c017f to your computer and use it in GitHub Desktop.
/**
* Created by: Toast <sam@gib.games>
* https://github.com/dorktoast/
* MIT License: https://opensource.org/license/mit
*/
using UnityEngine;
using System;
namespace GIB
{
/// <summary>
/// Command Line Argument handler
/// </summary>
public class CommandLineHandler : Singleton<CommandLineHandler>
{
#if UNITY_EDITOR
[Tooltip("Arguments to simulate command-line input in the editor.")]
public string EditorArgs;
private string[] editorArgsArray;
private void Start()
{
string newArgString = Application.productName + " " + EditorArgs;
editorArgsArray = newArgString.Split(' ');
}
private string[] GetCommandLineArgs()
{
return editorArgsArray;
}
#else
private string[] GetCommandLineArgs()
{
return Environment.GetCommandLineArgs();
}
#endif
/// <summary>
/// Attempts to retrieve the value of a command-line argument.
/// </summary>
/// <param name="argName">The name of the argument to look for.</param>
/// <param name="argValue">The value of the argument if found.</param>
/// <returns>True if the argument was found; otherwise, false.</returns>
public static bool TryGetArgValue(string argName, out string argValue)
{
var args = Instance.GetCommandLineArgs();
for (int i = 0; i < args.Length; i++)
{
if (args[i].Equals(argName, StringComparison.OrdinalIgnoreCase) && args.Length > i + 1)
{
argValue = args[i + 1];
return true;
}
}
argValue = null;
return false;
}
/// <summary>
/// Checks if a command-line argument exists.
/// </summary>
/// <param name="argName">The name of the argument to look for.</param>
/// <returns>True if the argument was found; otherwise, false.</returns>
public static bool GetArg(string argName)
{
var args = Instance.GetCommandLineArgs();
for (int i = 0; i < args.Length; i++)
{
if (args[i].Equals(argName, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment