I have created a .ini file parser for unity, This script enables you to easily create, edit and delete .ini files while being able to fetch and change values stored in them. ini files are mainly used to store settings, such as a games graphics settings, but can easily be used for anything else as its just a variable storage device. I have also added the ability for you to add comments to any variables stored, So if you were to edit the file in a text editor, comments will be shown next to them.

The code is show at the bottom of the post.

Usage:

The script can be called from any other without needing to be attached to a game object. It can be initialized with loading a file, or without, like so:

iniParser parser = new iniParser(); // Initialize without a file
iniParser parser = new iniParser("FILENAME"); // initialize with loading a file

Once set like so, You can begin to set variables like so:

parser.Set("Key","value");

If a file has been loaded, if there is a key in the .ini by that name it will be updated, Otherwise it is created. You can also add comments to the key like so:

parser.Set("key","value","Comment");

All changes must be saved, the save function will create the file as-well if it does not exist, like so:

parser.Save("FILENAME");

To fetch a value to be used somewhere else, You do it like so:

parser.Get("Key");

I have also added the ability to get an array with the whole line details: The key, the value and the comment (if exists), as an String array:

string[] details = parser.GetLine("key");

To remove a key, its as simple as:

parser.Remove("key");

To check if a .ini file exists, you use:

if(parser.DoesExist("Filename")){
   // Exists
} else {
   // Doesnt exist
}

 

There are two versions of this script, One that comes with Enum and Enum support, And one that is string based string based uses what’s shown above.

Enum based:

With this version you store the file names in the IniFiles Enum at the top of the script, This way you can easily get the names of all files from other scripts with loading and saving without the chance of entering the wrong name and causing problems. To load and Save a file with Enum names, You do this:

iniParser parser = new iniParser(IniFiles.FILENAME); // Initialize with loading a file

parser.Save(IniFiles.FILENAME);
parser.Load(IniFiles.FILENAME);
parser.DoesExist(IniFiles.FILENAME);

 

The files are saved in the Application DataPath. So if saved within editor they can be found here in “projectDir/Assets/filename.ini”, if by built launcher they would be here “gameDir/GameName_Data/filename.ini”.

In Summary:

If I wanted to create a graphic setting storage, I would do:

// This is using enum based so GRAPHICS is stored in the enum.

iniParser parser = new iniParser();

parser.Set("resolution","1980x1020");
parser.Set("windowed","False","Can either be True or False");
parser.Set("antiAlias","8","Can only be: 0, 1, 2, 4, 8");
parser.Set("quality","5");
parser.Set("vsync","2","Can only be: 0, 1, 2");

parser.Save(IniFiles.GRAPHICS);

The .ini file would show:

resolution=1980x1020
windowed=False //Can either be True or False
antiAlias=8 //Can only be: 0, 1, 2, 4, 8
quality=5
vsync=2 //can only be: 0, 1, 2

Code:

The script is fully commented with a summary for each method. Just create a new script c# in your project called “iniParser.cs” and copy the full code into that file, The code:

 

Enum based:

/*	
	.Ini file Parser
	Author: Tristan 'Kennyist' Cunningham - www.tristanjc.com
	Date: 13/04/2014
	License: Creative commons ShareAlike 3.0 - https://creativecommons.org/licenses/by-sa/3.0/
*/

using UnityEngine;
using System.Collections;
using System.IO;

/// <summary>
/// Names of all Ini files, Requires editing for your desired setup.
/// </summary>
public enum IniFiles{
	// Enum is being used so its easy to get the right names from other scripts, Less chance for errors
	// If you wish to not use an Enum, change "(IniFiles file)" to "(String file)" on the methods below 
	// (being: DoesExist, Save and load)
	GRAPHICS,
	AUDIO
}

/// <summary>
/// An .ini file parser that Creates and edits .ini files, With functions to fetch and delete values.
/// </summary>
public class iniParser {

	private ArrayList keys = new ArrayList();
	private ArrayList vals = new ArrayList();
	private ArrayList comments = new ArrayList();

	/// <summary>
	/// Initializes a new instance of the <see cref="iniParser"/> class without loading a file.
	/// </summary>
	public iniParser(){}

	/// <summary>
	/// Initializes a new instance of the <see cref="iniParser"/> class with loading a file.
	/// </summary>
	/// <param name="file">Name of the file you want to load.</param>
	public iniParser(IniFiles file){
		load(file);
	}

	/// <summary>
	/// Returns true if the file exists, or false if it doesnt.
	/// </summary>
	/// <param name="file">The selected file.</param>
	public bool DoesExist(IniFiles file){
		return File.Exists(Application.dataPath+"/"+file+".ini") ? true : false;
	}

	/// <summary>
	/// Set the variable and value if they dont exist. Updates the variables value if does exist.
	/// </summary>
	/// <param name="key">The variable name</param>
	/// <param name="val">The value of the variable</param>
	public void Set(string key, string val){
		for(int i = 0; i < keys.Count; i++){
			if(keys[i] == key){
				vals[i] = val;
				return;
			}
		}

		keys.Add(key);
		vals.Add(val);
		comments.Add("");
	}

	/// <summary>
	/// Set the variable and value if they dont exist including a comment. Updates the variables value and comment if does exist.
	/// </summary>
	/// <param name="key">The variable name</param>
	/// <param name="val">The value of the variable</param>
	/// <param name="comment">The comment of the variable</param>
	public void Set(string key, string val, string comment){
		for(int i = 0; i < keys.Count; i++){
			if(keys[i] == key){
				vals[i] = val;
				comments[i] = comment;
				return;
			}
		}

		keys.Add(key);
		vals.Add(val);
		comments.Add(comment);
	}

	/// <summary>
	/// Returns the value for the input variable.
	/// </summary>
	/// <param name="key">The variable name.</param>
	public string Get(string key){
		for(int i = 0; i < keys.Count; i++){
			if(keys[i].Equals(key)){
				return vals[i].ToString();
			}
		}
		return "";
	}

	/// <summary>
	/// Returns the Key, Value and comment of the choosen variable.
	/// </summary>
	/// <returns>String array containing the 3 values</returns>
	/// <param name="key">The variable name.</param>
	public string[] GetLine(string key){
		string[] list = new string[2];

		for(int i = 0; i < keys.Count; i++){
			if(keys[i].Equals(key)){
				list[0] = keys[i].ToString();
				list[1] = vals[i].ToString();
				list[2] = comments[i].ToString();
				return list;
			}
		}

		return list;
	}

	/// <summary>
	/// Removes the selected Variable including its value and comment.
	/// </summary>
	/// <param name="key">The variable name.</param>
	public void Remove(string key){
		for(int i = 0; i < keys.Count; i++){
			if(keys[i] == key){
				keys.RemoveAt(i);
				vals.RemoveAt(i);
				comments.RemoveAt(i);
				return;
			}
		}
		Debug.LogWarning("Key not found");
	}

	/// <summary>
	/// Save the specified file.
	/// </summary>
	/// <param name="file">The file name.</param>
	public void save(IniFiles file){
		StreamWriter wr = new StreamWriter(Application.dataPath + "/" + file + ".ini");

		for(int i = 0; i < keys.Count; i++){
			if(comments[i].Equals("")){
				wr.WriteLine(keys[i] +"="+ vals[i]);
			} else {
				wr.WriteLine(keys[i] +"="+ vals[i]+" //"+comments[i]);
			}
		}

		wr.Close();

		Debug.Log(file+".ini Saved");
	}

	/// <summary>
	/// Load the specified file.
	/// </summary>
	/// <param name="file">The file name.</param>
	public void load(IniFiles file){
		keys = new ArrayList();
		vals = new ArrayList();
		comments = new ArrayList();

		string line = "", dir = Application.dataPath +"/"+ file +".ini";
		int offset = 0, comment = 0;

		try{
			using(StreamReader sr = new StreamReader(dir)){
				while((line = sr.ReadLine()) != null){
					offset = line.IndexOf("=");
					comment = line.IndexOf("//");
					if(offset > 0){
						if(comment != -1){
							Set(line.Substring(0,offset),line.Substring(offset+1,(comment - (offset+1))),line.Substring(comment+1));
						} else {
							Set(line.Substring(0,offset),line.Substring(offset+1));
						}
					}
				}
				sr.Close();
				Debug.Log(file + " Loaded");
			}
		} catch(IOException e){
			Debug.Log("Error opening "+file+".ini");
                        Debug.LogWarning(e);
		}
	}

	/// <summary>
	/// How many keys are stored.
	/// </summary>
	public int Count(){
		return keys.Count;
	}
}

 

String Based:

/*	
	.Ini file Parser
	Author: Tristan 'Kennyist' Cunningham - www.tristanjc.com
	Date: 13/04/2014
	License: Creative commons ShareAlike 3.0 - https://creativecommons.org/licenses/by-sa/3.0/
*/

using UnityEngine;
using System.Collections;
using System.IO;

/// <summary>
/// An .ini file parser that Creates and edits .ini files, With functions to fetch and delete values.
/// </summary>
public class iniParser {

	private ArrayList keys = new ArrayList();
	private ArrayList vals = new ArrayList();
	private ArrayList comments = new ArrayList();

	/// <summary>
	/// Initializes a new instance of the <see cref="iniParser"/> class without loading a file.
	/// </summary>
	public iniParser(){}

	/// <summary>
	/// Initializes a new instance of the <see cref="iniParser"/> class with loading a file.
	/// </summary>
	/// <param name="file">Name of the file you want to load.</param>
	public iniParser(string file){
		load(file);
	}

	/// <summary>
	/// Returns true if the file exists, or false if it doesnt.
	/// </summary>
	/// <param name="file">The selected file.</param>
	public bool DoesExist(string file){
		return File.Exists(Application.dataPath+"/"+file+".ini") ? true : false;
	}

	/// <summary>
	/// Set the variable and value if they dont exist. Updates the variables value if does exist.
	/// </summary>
	/// <param name="key">The variable name</param>
	/// <param name="val">The value of the variable</param>
	public void Set(string key, string val){
		for(int i = 0; i < keys.Count; i++){
			if(keys[i] == key){
				vals[i] = val;
				return;
			}
		}

		keys.Add(key);
		vals.Add(val);
		comments.Add("");
	}

	/// <summary>
	/// Set the variable and value if they dont exist including a comment. Updates the variables value and comment if does exist.
	/// </summary>
	/// <param name="key">The variable name</param>
	/// <param name="val">The value of the variable</param>
	/// <param name="comment">The comment of the variable</param>
	public void Set(string key, string val, string comment){
		for(int i = 0; i < keys.Count; i++){
			if(keys[i] == key){
				vals[i] = val;
				comments[i] = comment;
				return;
			}
		}

		keys.Add(key);
		vals.Add(val);
		comments.Add(comment);
	}

	/// <summary>
	/// Returns the value for the input variable.
	/// </summary>
	/// <param name="key">The variable name.</param>
	public string Get(string key){
		for(int i = 0; i < keys.Count; i++){
			if(keys[i].Equals(key)){
				return vals[i].ToString();
			}
		}
		return "";
	}

	/// <summary>
	/// Returns the Key, Value and comment of the choosen variable.
	/// </summary>
	/// <returns>String array containing the 3 values</returns>
	/// <param name="key">The variable name.</param>
	public string[] GetLine(string key){
		string[] list = new string[2];

		for(int i = 0; i < keys.Count; i++){
			if(keys[i].Equals(key)){
				list[0] = keys[i].ToString();
				list[1] = vals[i].ToString();
				list[2] = comments[i].ToString();
				return list;
			}
		}

		return list;
	}

	/// <summary>
	/// Removes the selected Variable including its value and comment.
	/// </summary>
	/// <param name="key">The variable name.</param>
	public void Remove(string key){
		for(int i = 0; i < keys.Count; i++){
			if(keys[i] == key){
				keys.RemoveAt(i);
				vals.RemoveAt(i);
				comments.RemoveAt(i);
				return;
			}
		}
		Debug.LogWarning("Key not found");
	}

	/// <summary>
	/// Save the specified file.
	/// </summary>
	/// <param name="file">The file name.</param>
	public void save(string file){
		StreamWriter wr = new StreamWriter(Application.dataPath + "/" + file + ".ini");

		for(int i = 0; i < keys.Count; i++){
			if(comments[i].Equals("")){
				wr.WriteLine(keys[i] +"="+ vals[i]);
			} else {
				wr.WriteLine(keys[i] +"="+ vals[i]+" //"+comments[i]);
			}
		}

		wr.Close();

		Debug.Log(file+".ini Saved");
	}

	/// <summary>
	/// Load the specified file.
	/// </summary>
	/// <param name="file">The file name.</param>
	public void load(string file){
		keys = new ArrayList();
		vals = new ArrayList();
		comments = new ArrayList();

		string line = "", dir = Application.dataPath +"/"+ file +".ini";
		int offset = 0, comment = 0;

		try{
			using(StreamReader sr = new StreamReader(dir)){
				while((line = sr.ReadLine()) != null){
					offset = line.IndexOf("=");
					comment = line.IndexOf("//");
					if(offset > 0){
						if(comment != -1){
							Set(line.Substring(0,offset),line.Substring(offset+1,(comment - (offset+1))),line.Substring(comment+1));
						} else {
							Set(line.Substring(0,offset),line.Substring(offset+1));
						}
					}
				}
				sr.Close();
				Debug.Log(file + " Loaded");
			}
		} catch(IOException e){
			Debug.Log("Error opening "+file+".ini");
                        Debug.LogWarning(e);
		}
	}

	/// <summary>
	/// How many keys are stored.
	/// </summary>
	public int Count(){
		return keys.Count;
	}
}

 

Categories: CodeUnity

Leave a Reply

Your email address will not be published.