Unity: .ini file parser script (c#)

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:

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

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:

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

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

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:

To remove a key, its as simple as:

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

 

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:

 

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:

The .ini file would show:

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:

 

String Based:

 

Leave a Reply

Your email address will not be published. Required fields are marked *


5 × = thirty five