Skip to content

Instantly share code, notes, and snippets.

@openroomxyz
Created April 18, 2020 20:02
Show Gist options
  • Select an option

  • Save openroomxyz/454af994c2d394d73df6847e8e5c4a02 to your computer and use it in GitHub Desktop.

Select an option

Save openroomxyz/454af994c2d394d73df6847e8e5c4a02 to your computer and use it in GitHub Desktop.
Unity : How can a script itself creates gameobject at Runtime and attach itself to it or [Creating game-object directly from script that is not attracted to any game objects ]?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SelfInstanciated : MonoBehaviour
{
[RuntimeInitializeOnLoadMethod]
static void Init()
{
GameObject instance_of_game_object = new GameObject();
instance_of_game_object.transform.position = Vector3.zero;
instance_of_game_object.name = "Self_InstanciatedGameObject_byHisScript";
instance_of_game_object.AddComponent<SelfInstanciated>();
/*
* Script itself creates gameobject at Runtime and attach itself to it.
*/
}
// Start is called before the first frame update
void Start()
{
Debug.Log("Hello! I am born from script! ( No game Object needed!)");
}
// Update is called once per frame
void Update()
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment