Hi, i m randomly spawning moving platforms and i want them to parent player when he jumps on them so he moves along with them. I m struggling to find way to make prefab a parent to some game object (Player in this case). I would appreciate any help.
You can make any GameObject the parent of another simply by setting the transform.parent to the other GameObjectâs transform. you can handle the OnCollision event on the platform. When the player collides with the platform, the collision object will have a reference to the player so you can set the platform to be the players parent there.
Hi , thank u for replay ,I already tried that and it s not working . It works if i want to pair game object with another game object , but not when im trying to pair randomly spawned prefab with game object . Maybe i did smthing wrong . Here s code i used
public class PlayerAttach : MonoBehaviour
{
public GameObject Player;
private void OnTriggerEnter(Collider other)
{
if (other.gameObject == Player)
{
Player.transform.parent = transform;
}
}
private void OnTriggerExit(Collider other)
{
if (other.gameObject == Player)
{
Player.transform.parent = null;
}
}
}
Iâm assuming that your Player variable is assigned the prefab from your project folder. Is that right?
In that case there are two things youâd need to change:
You wrote:
if (other.gameObject == Player)
I donât have my IDE open at the moment to test, but Iâm pretty sure this will not work. other.gameObject may be an instance of the Player prefab, but that does not mean that they are equal. You will need to use a different way to identify if other.gameObject is the player or not. One popular way is to set the playerâs tag to âPlayerâ and then use CompareTag to check the objects tag. You can see a clear example of this in the documentation:
the second thing:
You wrote:
Player.transform.parent = transform;
But I think you actually meant:
other.transform.parent = transform;
In fact, you shouldnât need a reference to the Player prefab in this code at all.
Now, on the other hand, if Player is actually assigned the player object thatâs in your scene, then I donât know why your code wouldnât have worked, but you might as well make these same changes anyway, so that your code does not rely on being linked to the player.
Sorry for late reply , my player is not prefab , but my platforms are .
I tried it out with tags and i get this error in console:
Setting the parent of a transform which resides in a Prefab Asset is disabled to prevent data corruption (GameObject: âPlayerâ).
I m still new to unity and all of this.