- Home /
Adding children to the list during the game.
I have objects stacked throughout the game. And each object added to the top becomes the child of the bottom object (lefthand). I'm trying to find the last child and reach his place. I'm trying to add kids to my list with the code below. However, when I check, children are not added to the list. There must be a mistake but I couldn't find what happened.
public class move : MonoBehaviour
{
public GameObject lefthand;
public GameObject righthand;
public Animator anim;
public float speed;
public GameObject lefttrig;
public List<GameObject> childleft = new List<GameObject>();
private void Start()
{
if (lefthand.transform.childCount>0)
{
foreach (Transform t in lefthand.transform)
{
childleft.Add(t.gameObject);
}
}
}
private void Update()
{
GameObject lastchild = childleft[childleft.Count-1];
if (lefthand.transform.childCount>1)
{
lefttrig.transform.position = lastchild.transform.position;
}
}
When I control the number of children it increases. There is no problem with it.
Clear your list after you are done adding, also, look into other collection types I'm not sure which one, but one is more performant when adding things to first and last (I think LinkedList)
I did not understand the cleaning after the addition was finished. The addition does not end throughout the game.
Answer by jmgek · Sep 22, 2020 at 07:22 PM
You should be really thinking about making a parent class and have a List<GameObject> children
that you add to every time you attach a child.
public class Child : Parent{
void AddToParent(){
//Add to parent transform
base.children.Add(this);
Your answer
Follow this Question
Related Questions
Make a simple tree 1 Answer
A node in a childnode? 1 Answer
Find out if two children/gameObjects have the same parent. 2 Answers