Creating a child gameObject from a parent script while running (aka not using eg. start() or Selection)
Hello... First question:
I'd like to have a parent "TreeCreator" class declare, initialize, and spawn a new child gameObject, "Heart" with the component heart.cs (I saw the addComponent thing so that shouldn't be a problem).
Here's what I have so far (from another example):
[MenuItem("GameObject/Create Empty Child #&c")]
// Use Shift+Alt+c
// For initialization
static void createEmptyChild () {
GameObject heart = new GameObject("Heart");
Instantiate (heart,
Vector3(Transform.position.x, Transform.position.y, Transform.position.z),
Quaternion.identity);
heart.transform.parent = tree.activeTransform.parent;
heart.transform.Translate(Selection.activeTransform.position);
}
I get an error for tree.activeTransform.parent //UnityEngine.GameObject doesn't contain this I understand from another tutorial that if I did "Selection.activeTransform.parent" it would work but I don't want to have to select each object that I want to create a child in because I will be generating thousands of these "TreeGeneration" gameObjects all with their own "Heart" class.
Any help or push in the right direction is greatly appreciated.
Oh also I did declare the tree already... Here it is:
GameObject tree = this.gameObject; //This is an error because of "this"
Figured it out: $$anonymous$$ods please still verify question because there isn't a clearer example for parent script to child creation then this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
public class TreeCreator : $$anonymous$$onoBehaviour {
void Start(){
createHeart ();
}
void createHeart () {
GameObject heart = new GameObject ("Heart");
heart.transform.parent = this.transform;
heart.transform.position = this.transform.position;
if (this.transform.parent != null) {
Destroy (heart);
Destroy (this);
Debug.Log ("Deleted tree and heart due to incorrect referencing.");
} else {
Debug.Log ("Tree -> Heart Created", this);
}
}
}
Your answer
Follow this Question
Related Questions
Can not access GetComponentInParent ( ). usegravity 1 Answer
NullReferenceException when trying to access parent 0 Answers
How to set GameObject created by MenuItem as a child of Canvas 0 Answers
Moving grabbed object OnTriggerStay2D 0 Answers
How to add a texture to all the child game objects under a parent ? 0 Answers