Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GameObject doesnt allow more than one child

So basically I am trying to add a bunch of children to a GameObject. The parent GameObject is called SnakeHead while all the other GameObjects are called SnakeBodyParts

public class GameController : MonoBehaviour {
    public GameObject snakeHead;
    public GameObject snakeBodyPart;
    public List<GameObject> snakeBodyParts;

    void Start() {
        snakeBodyParts = new List<GameObject>();
        Instantiate<GameObject>(snakeHead);

        for (int i = 0; i < 4; i++)
        {
            var newObj = Instantiate<GameObject>(snakeBodyPart);
            newObj.transform.position = new Vector3(snakeHead.transform.position.x, snakeHead.transform.position.y - (i + 1), 0);
            newObj.transform.SetParent(snakeHead.transform);
            snakeBodyParts.Add(newObj);
        }
    }
}

So it looke like snakeHead.transform.childCount; is 1. Can anyone explain to me this kind of behaviour? Both SnakeHead and SnakeBodyPart are a simple Sphere added as a 3D Object to my project.

like image 530
user2877820 Avatar asked Sep 15 '25 23:09

user2877820


1 Answers

I assume that snakeHead and snakeBodyPart are both prefabs.

The problem is that you are setting the parent of the snakeBodyPart with the snakeHead prefab instead of the instantiated snakeHead.

When you instantiate snakeHead, you are supposed to store it to a temporary variable the use it to set the parent of each instantiated snakeBodyPart(newObj).

Instantiate<GameObject>(snakeHead) should be GameObject snakeHaedObj = Instantiate<GameObject>(snakeHead); then you can do snakeHaedObj .transform.childCount; later on to check the count and set the parent of each snakeBodyPart with newObj.transform.SetParent(snakeHaedObj.transform);.

Something like this:

public GameObject snakeHead;
public GameObject snakeBodyPart;
public List<GameObject> snakeBodyParts;

GameObject snakeHaedObj;

void Start()
{
    snakeBodyParts = new List<GameObject>();
    snakeHaedObj = Instantiate<GameObject>(snakeHead);

    for (int i = 0; i < 4; i++)
    {
        var newObj = Instantiate<GameObject>(snakeBodyPart);
        newObj.transform.position = new Vector3(snakeHead.transform.position.x, snakeHead.transform.position.y - (i + 1), 0);
        newObj.transform.SetParent(snakeHaedObj.transform);
        snakeBodyParts.Add(newObj);
    }
}

Note that childCount will only return the direct child not but not Objects under the child. Take a look at this post for how to do that.

like image 94
Programmer Avatar answered Sep 17 '25 12:09

Programmer