- Home /
Set child of a parent
Hi, I am making a 2D platform game in unity. I am having trouble getting my player to move with the platform. The way i am trying to do this is by making the player a child of the platform so it moves with it. But the problem is that i have two colliders on my player "a box and a circle collider". When my player jumps on the platform, all of the players child is platforms child expect the circle collider. I don't know how to make it so the circle collider is included when jumping on the platform. I have some pictures that illustrate the problem:
This is how the player and platforms look:
.
This this how the the two colliders are set on the player
the rest is here https://imgur.com/a/87G8Gk0
This is the code:
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Player")
{
collision.collider.transform.SetParent(transform);
moving = true;
}
}
private void OnCollisionExit2D(Collision2D collision)
{
if (collision.gameObject.tag == "Player")
{
collision.collider.transform.SetParent(null);
moving = false;
}
}
void FixedUpdate()
{
if (moving)
{
transform.position += (velocity * Time.deltaTime);
}
}
Hi!
I've been trying to recreate your issue, but without success.
I would suggest you to make sure that there is no other scripts acessing circle collider that could interfer with your parenting, however, you can try to do this as an workaround:
if (collision.gameObject.tag == "Player")
{
List<Transform> playerChilds = new List<Transform>();
foreach (Transform child in collision.collider.transform)
playerChilds.Add(child);
collision.collider.transform.SetParent(transform);
moving = true;
for (int i = 0; i < playerChilds.Count; i++)
playerChilds[i].SetParent(collision.collider.transform);
}
Basically, we are storing all childs of player before parenting into a List (you will need to use using System.Collections.Generic namespace to access List type, and after parenting we loop through all stored childs and parent them to the player back. That will ensure that circle will stay parented.
However, this is not the greatest way to do it, but it will work.
Hope that helps.
Your answer
Follow this Question
Related Questions
Minimize And Maximize An application 1 Answer
how to develop a matching game based on a picture and a list of words? 1 Answer
Making A Tileset 1 Answer
more cubes if there are more rounds 2 Answers
problem with the change's speed between 2 texture using a switch script, how can i speed it up? 1 Answer