- Home /
transform.parent not working
void OnCollisionEnter2D(Collision2D stay){
if (stay.gameObject.tag == "Player" && !onPlatform){
player.transform.parent = transform;
onPlatform = true;
}
}
I need to parent my character to a moving platform when they collide, simple as that. onPlatform variable will become true, but the parent instruction will not be executed. Any help appreciated.
"onPlatform variable will become true, but the parent instruction will not be executed" this means putting a debug log is useless cause i told you the if it works...and the name...rly i dont think that changing the varable name will make a miracle. Here is the entire code: using UnityEngine; using System.Collections;
public class LefttoRightPlatform : $$anonymous$$onoBehaviour {
int direction = 1;
GameObject player;
bool onPlatform = false;
void Start(){
player = GameObject.Find ("PlayerChar");
player.transform.parent = null;
}
void Update () {
player.transform.parent = null;
if (transform.position.x < -64)
direction = 1;
if (transform.position.x > -43)
direction = -1;
transform.Translate (Vector2.right * direction * 2f * Time.deltaTime);
}
void OnCollisionEnter2D(Collision2D stay){
if (!onPlatform){
player.transform.parent = gameObject.transform;
Debug.Log("shit");
onPlatform = true;
}
}
}
Answer by MrAkroMenToS · Dec 16, 2014 at 08:38 PM
Use SetParent instead of what you are using. And make sure you set onPlatform false when exiting. On the other hand i recommend you to move this to the player's movement. and use this structure if you do so
void OnCollisionEnter2D(Collision2D stay){
if (stay.gameObject.tag == "Platform" && !onPlatform){
//Here you should set the parent of transform to stay.gameObject.transform, you can use both transform.parent or SetParent, it's up to you
}
}
Transform.parent= aught to work. i use it all the time. I suspect something else is wrong with his code.
He needs to properly trace and figure out what assumption he is making is false.
I edited the answer i think there will be something with the player gameobject. It would be better to place this logical block to the player's script because it should be there.
But if you exit from the platform you sould unparent your player.
++If this code is already in the player's code it's logically not good because you set the parent to player. (player will be player's parent)
Ok $$anonymous$$r.Akro i will try using SetParent()...and if it wont work ill move the script to the character
Answer by MrAkroMenToS · Dec 16, 2014 at 09:06 PM
It is very simple you make your player.transform.parent null in every update. Make sure you only make it null if you exit from the platform