Question by
Moy01 · Apr 03, 2021 at 04:31 PM ·
gameobjectinstantiateruntime-generation
How to create a game object at run time
Hi all, I'm trying to create a GameObject at runtime but it doesnt work if there is no parent created, if that is the case i want to create it dynamically but apparently the code is not being executed Does anyone know why or another way to do so Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SetParentOfThisObject : MonoBehaviour {
public string nameParent;
public GameObject genericGO;
public Transform parent;
void Start () {
parent = checkForParentExistence(nameParent);
SetParent(parent);
}
//Sets this game object's transform as child of the Transform given to this function
public void SetParent(Transform parent)
{
gameObject.transform.parent = parent;
}
//Performs a search of a game object called same as the given string
public Transform checkForParentExistence(string transformName)
{
Transform parentGO = GameObject.Find(transformName).GetComponent<Transform>();
//If there is not a game object with the given name, we'll try to create a new one using a dummy GameObject
if(parentGO == null)//<-Apparently my code is not getting to this line
{
GameObject foo = Instantiate(genericGO, Vector3.zero, Quaternion.identity);
foo.name = transformName;
parentGO = foo.transform;
}
return parentGO;
}
}
Comment
Your answer
