Parenting player to car on click.

I am creating a game which I would like the player to be able to click a vehicle/car they would like to get in.

So I know the code

player.parent = vehicle;

will attach them, but how do I say that If the player clicks on the object, the player will parent with the vehicle and ALSO change the smooth follow script to the vehicle instead of the player?


To detect clicks on an object, the object must have a Collider Component. You can then use the OnMouseDown or OnMouseUp event handler functions.

The "SmoothFollow" script which comes in Unity's Standard Assets package has a public variable defined as:

var target : Transform;

Which means you can set this variable from any external source.

So, combining all these together would give you something that might look like this. If this script is placed on the vehicle, you can use the variable "transform" to refer to the object's own transform. This script also assumes there's only one instance of "SmoothFollow" in your scene.

function OnMouseUp() {
    player.parent = transform;
    FindObjectOfType(SmoothFollow).target = transform;

If your player isn't in the correct position when you click on the vehicle, it will stay in that relative position once parented, so you might want to set the player's localPosition to correct this, after parenting it to the vehicle.