How to add additional Data to a game object?

I try to make a game with Animals. I have a different prefabs of different animals which all use the same state machine script in C# at the moment.

Now I managed to place a dynamic created instance of one of my prefabs in my game with:

GameObject prefab = Resources.Load ("horse") as GameObject;
GameObject instance = Instantiate(prefab, new Vector3(315, 14, 190), transform.rotation) as GameObject;

I would like to give the instance additional data like an ID or a name. How can I do that?

Add a component (script) with the desired variables.

–Eric

Should I use the FSM script that all prefab animals use or better use a new one and add this to the horse prefab? I’m still new to Unity and not sure if I understand the concept correct. At the moment I use the start method in the main camera to create a dynamical horse object. How can I set the ID variable from there in the script from the horse instance?

GetComponent

–Eric

In addition to what’s been mentioned, you could create a new script and add it to the Horse prefab, such as:

using UnityEngine;
using System.Collections;

public class Horse : MonoBehaviour {

    public string name = "Horse";

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {

    }
}

Then you could instantiate the horse and change the Horse component properties using:

GameObject prefab = Resources.Load ("horse") as GameObject;
GameObject instance = Instantiate(prefab, new Vector3(315, 14, 190), transform.rotation) as GameObject;
Horse horse = instance.GetComponent("Horse") as Horse;
horse.name = "Mister Ed";

Thank you that example helps me alot :slight_smile: