2
\$\begingroup\$

I have a prefab of a "generic unit;" each one has a script with some public variables: name, health, and attack.

Currently, I am manually making copies of that prefab and editing their names, health and damage values in the inspector. This seems unwise to me.

I would rather be able to make a simple file for each unit type, containing its important information, like this:

name = "Archer"
health = 3
attack = 1

And so on. Then, I would like to be able to turn that into actual GameObjects in Unity, presumably by instantiating the prefab and filling in its values with values from the file.

I could then make a script that runs when the game begins and iterates through, making all the objects I need.

However, I do not know the proper way to go about doing this. Is there some way to read files and slot values into variables of a script?

To be clear, I would like to be able to tell Unity to make an Archer, then have it read the Archer file, look up its values for health and attack, then instantiate a copy of the Generic Unit prefab and slot the values that it read into the public variables of a script component of the newly-created game object.

\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

Short of using a third-party parser or writing your own parser for any file format, Unity 5.3 has a built-in JsonUtility class that can automatically parse a JSON string and apply its values to a class:

JsonUtility.FromJsonOverwrite: Overwrite data in an object by reading from its JSON representation.

For example, say you had a Creature class:

public class Creature : MonoBehaviour {
    public string creatureName;
    public int health;
    public int attack;
}

You could have a JSON file named Archer.json placed in your Resources folder containing:

{
    "creatureName": "Archer",
    "health": 3,
    "attack": 1
}

You could then load and assign the JSON values to a Creature like so:

// Load the JSON file
TextAsset textAsset = (TextAsset)Resources.Load("Archer"); // Don't include the .json extension
string jsonString = textAsset.text;

// Instantiate a Creature, assuming you have a `GenericCreature` prefab in your Resources folder
GameObject prefab = (GameObject)Resources.Load("GenericCreature");
GameObject newObject = (GameObject)Instantiate(prefab);
Creature newCreature = newObject.GetComponent<Creature>();

// Assign the Archer JSON values to the Creature
JsonUtility.FromJsonOverwrite(jsonString, newCreature);
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .