- Home /
Parenting Player to platforms, not parenting on the second platform?
So I have a game with 2 moving platforms, and I have attached a parenting script to each platform so that I stay on the platform as it moves. both platform scripts work perfectly until I try to move from platform 1 to platform 2, I am parented to platform 1 until I move off of it, but it I don't get parented to the second platform, It does the same thing when moving from platform 2 to platform 1. I think it is because my player touches the second platform before it has a chance to un-parent from the first, but this is my first game so I could use some help.
They are basically the same, each is attached to the platform itself.
The only difference between the two is the Tags
Any help would be greatly appreciated. Thanks in advance!
Answer by Nikaas · Dec 17, 2017 at 07:53 PM
The problem is probably that Platform1 is "deparenting" the player after Platform2 changed player's parent to self(Platform2).
Have you tried next:
void OnCollisionExit(Collision collision)
{
if (collision.gameObject.CompareTag("Player1") && collision.transform.parent == gameObject.transform)
{
collision.transform.parent = null;
}
}
On a sidenote: why you use tags for this? If you have 50 platforms you will need 50 tags. Wouldn't collision.transform.parent = gameObject.transform; work? Tags are usually used to group up objects. And it is better to use gameObject.CompareTag("someTag"); than gameObject.tag == "someTag".
Thank you that worked perfectly, and to answer your first question I'm new to this, but I applied what you told me about the tags and its going to save me a lot of time, thanks!
Answer by WorldEater · Dec 17, 2017 at 10:07 PM
First of all the GameObject.FindGameObjectWithTag funktion is very expensive and should be avoided if possible. I would also suggest having the same script on both platforms as this will make things a lot easier in the long run.
Try this:
void OnCollisionEnter(Collision collision){
if(collision.collider.tag == "player1"){
collision.collider.transform.SetParent (transform);
Debug.Log ("player hit: " + transform.name);
}
}
void OnCollisionExit(Collision collison){
if (collison.gameObject.tag == "player1") {
collison.collider.transform.SetParent (null);
Debug.Log ("player left: " + transform.name);
}
}
If that dose not work, check the console to figure out what is not working.