I’d like to create an empty gameobject dynamically from code and add it to the scene. I can’t seem find anything on how to do this, everything is just for spawning prefabs, which I don’t really want to do. I assume I can create a gameobject just by calling new GameObject(), but then how do I add that to the scene?
using UnityEngine;
using System.Collections;
public class TempTEST : MonoBehaviour {
//store gameObject reference
GameObject objToSpawn;
void Start()
{
//spawn object
objToSpawn = new GameObject("Cool GameObject made from Code");
//Add Components
objToSpawn.AddComponent<Rigidbody>();
objToSpawn.AddComponent<MeshFilter>();
objToSpawn.AddComponent<BoxCollider>();
objToSpawn.AddComponent<MeshRenderer>();
}
}
Here some free code!
I’m pretty sure the gameObject gets added automatically upon creation. (This is also why gameObject creation has to be done within the main thread.)
Hey late answer i know, judging from what you are trying to do, this could be helpfull
private GameObject EmptyObj;
public GameObject prefab;
void Start()
{
EmptyObj = new GameObject("name");
// in case you want the new gameobject to be a child
// of the gameobject that your script is attached to
EmptyObj.transform.parent = this.gameObject.transform;
// and in case you want to throw other gameobjects into your new gameobject
prefab.transform.parent = EmptyObj.gameObject.transform;
}
I know that there’s allready an answer, but this could be helpful to others.
I just did this in unity, so my answer is 100% solution - test for yourself and then please upvote.
-
Create a empty game object (GameObject->Create Empty’
-
Drag and drop this empty GameObject into your ‘Prefab’ folder in the projects/assets/. If you don’t have such a folder, create it.
-
Delete the empty GameObject from the hierarchy
-
Create a script with this language…
using UnityEngine;
using System.Collections;public class test : MonoBehaviour {
public GameObject emptyGameObjectPrefab; void Start () { Instantiate(emptyGameObjectPrefab, transform.position,Quaternion.identity); }
}
-
drag and drop the empty GameObject prefab onto the script variable in the inspector that we just created called ‘public GameObject emptyGameObjectPrefab’.
That’s it…step by step from start to finish. This is tested in Unity 4.2 as of 5 seconds ago.
Omg thank you i love you i can give you some chocojuline