How To Make An Object A Child Of Another Object (SCRIPT)

So let’s say I have 3 objects: object1, object2, object3. I want to know how to make it so that i can make object1 a child of object 2, but in javascript. so something like this:

if(Input.GetKey(KeyCode.F))
{
    //make object1 a child of object 2
}

this isn’t how the script will be exactly. But i want it so that the object1 becomes a child of object2.

Thanks

You can use this through the objects transform.parent call and assign it’s parent the assigned transform

for example:

object1.transform.parent = object2.transform 
//object1 is now the child of object2

we have 3 objects: object1, object2, object3.
i can make object1 a child of object 2,
//using this line of code

object1 .transform.SetParent(object2 .transform.parent);

Anyway to undo that?,Anyway to undo the parenting,Anyway to undo the parenting?

Also if you want to have the same transform as the parent you could first take the transform from the parent and afterward make it the parent.

object1.transform.position = object2.transform.position;
object1.transform.parent = object2.transform;

If there is a better way, please let me know.