Parenting Example Script
Download and inport this Unity Package to take a look at the scripts, scene, and see them work.
What's included:
Parenting (Scene)
MoveObject.cs (Script)
ObjectDetails.cs (Script)
SwitchParent.cs (Script)
Parenting (Scene)
This scene has a cube on the left and a sphere on the right and a capsule in the center. The capsule is the object that changes its parent when you press a button. It's default parent is an empty game object called Empty Object.
There is a UI Canvas with two buttons: Switch Parent and Reset Parent.
MoveObject.cs (Script)
This script is attached to both the cube and the sphere with the sphere having Move Opposite checked.
The script has the object it is attached to move when the Up Arrow or W key is pressed or when the Down Arrow or S key is pressed.
ObjectDetails.cs (Script)
This script is attached to the object that is changing parents (the capsule) to keep track of its original parent.
It sets its Original Parent parameter upon playing the scene.
SwitchParent.cs (Script)
SwitchParent has functions for both buttons to run, so I attached it to the Canvas. I set the Affected Object to the Capsule, Parent Option 1 to the Cube, and Parent Option 2 to the Sphere within Unity.
Note: Start()
and Update()
aren't needed here, but I left them in, in case it makes it easier for you to understand where the two custom functions would appear.
ChangeParent()
checks to see if the affected object is parented to the first option. If it is, it switches to the second option. If it isn't, it switches it to the first.
ResetParent()
looks at the ObjectDetails script attached to the affected object to determine and set the parent to the original parent.
To call these functions, I have the button objects reference the SwitchParent script and call the specific function:
Test it!
When playing, the capsule should move with the parent object as well as appear as a child object in the Hierarchy window. When it's parented by its original parent, it will not move.
Last updated