how to add prefab to gameobject?
I'm trying to have 'foundation' as a child of 'empty' but with my code it doesn't do that but it also gives no errors, what am I doing wrong?
public List<GameObject> foundations = new List<GameObject>();
public List<GameObject> levels = new List<GameObject>();
public List<GameObject> roofs = new List<GameObject>();
public BuildSystem buildSystem;
GameObject empty;
private int x = 0;
public void CreateNewBuilding()
{
x++;
empty = new GameObject("Building" + x);
}
public void StopBuilding()
{
Destroy(empty);
x--;
}
public void AddFoundation(GameObject foundation)
{
foundations.Add(foundation);
buildSystem.NewBuild(foundation);
foundation.transform.SetParent(empty.transform);
}
Answer by cotevelino · May 19, 2021 at 03:50 AM
Try to use transform.SetParent(wantedParent), store the new foundation that was instanced and after spawn assign the parent to it. hope it helps.
docs: https://docs.unity3d.com/ScriptReference/Transform.SetParent.html
I don't understand what you are saying. Right now I'm using foundation.transform.SetParent(empty.transform) if I use foundation.transform.SetParent(empty) there is an error because empty is a gameobject.
Well then idk why it doesn't work. Maybe u forgot somth in code or forgot to set references
Answer by Owen-Reynolds · May 19, 2021 at 07:54 PM
A comment -- instead of new GameObject
it's almost always better to Instantiate a prefeb. Even for an empty you probably want it set to a different layer, and want a script on it at (at least a data-only script). You can do that in code, but a prefab makes it easier.
As far as setting a parent, any way works. If G is a gameObject and Empty is another, then
G.transform.parent=Empty.transform;
is fine or
G.transform.SetParent(Empty.transform);
or when you Instantiate G use the option to set a parent. I've used them all and they're the same. If there's a problem it's something else. Look at the errors -- is it saying something is null? Maybe foundation isn't being created?
Your answer
Follow this Question
Related Questions
Foreach loop not going through all elements 1 Answer
How can the pivot point of a object be changed during Runtime? 0 Answers
Following object (arrow) slides off of a object 1 Answer
rotate child relative to parent,rotating child object in relation to parent 2 Answers
Child always on parent top to get the number of dice 0 Answers