- Home /
Adding a prefab to gameObject at a certain position in runtime
Hello all,
I'm building a 2D snake game, consists of three images: head, tail, body
I'd like to add a the "body" prefab of the snake body once it ate a food. I need to place the "body" between the head and the tail each time as it increments. see pic:
I see this as a list of body parts that increments as the snake eat. List of x prefabs with n items, such as: x=1: snake head, x=n (the last position) is the tail. and in between is the "body". The "body" should be added always at the position of n-1, right before the tail.
this is the code I have so far... and it will add the body part but on top of the current body.
public void AddBodyPart()
{
GameObject _belly = Resources.Load<GameObject>("SnakeTileStraightSwallow") as GameObject;
Transform part = (Instantiate(_belly, snakeBodyPart[snakeBodyPart.Count-1].position, snakeBodyPart[snakeBodyPart.Count - 1].rotation) as GameObject).transform;
if (!snakeBodyPart.Contains(part))
{
part.transform.SetParent(gameObject.transform, false);
snakeBodyPart.Add(part);
}
}
Your answer
Follow this Question
Related Questions
Creating an array of prefabs? 4 Answers
use list of gameobjects transform in raycast 0 Answers
Sorting list of Transforms 1 Answer
Change sprite color on GameObjects from a list. 1 Answer
Keep adding targets to a list 2 Answers