- Home /
Add character into scene by script
I'm facing a problem with trying to add a character into a scene by C# script. Is this possible to do? I've only seen script to insert objects to a scene but not a character or prefab. Any clue to achieve this?
Answer by BlueHat · Apr 03, 2014 at 09:50 AM
You're looking for GameObject.Instantiate(Object origional) http://docs.unity3d.com/Documentation/ScriptReference/Object.Instantiate.html
On your script make a public GameObject called Prefab. Then in your scene link the prefab into the script in the inspector. Then simply use Object.Instantiate().
public GameObject Prefab;
private List<GameObject> listOfGameObjects;
void Start()
{
listOfGameObjects = new List<GameObject>();
GameObject NewEntity = GameObject.Instantiate(Prefab, Vector3.zero, Quaterion.identity) as GameObject;
listOfGameObjects.Add(NewEntity);
}
The code above will create a new object from your prefab when it starts and will add it to a list of GameObjects. I've not tested it though so there may be a spelling mistake or syntax error in there but that's the idea. Check the documentation link as well :)
Answer by OSG · Apr 03, 2014 at 09:54 AM
Character can be a prefab, so lets say that we have one. (c# code):
public class CharacterGenerator: MonoBehaviour {
public GameObject charPrefab;
void Awake() {
Instantiate(charPrefab, Vector3.zero, Quaternion.identity);
}
this will generate character in zero coordinates.
Your answer