Rotates the transform so the forward vector points at /target/’s current position.
Then it rotates the transform to point its up direction vector in the direction hinted at by the
worldUp vector. If you leave out the
worldUp parameter, the function will use the world y axis.
So if I want the gameObject to look at the mouse pointer in a 2D top down game, I could use the following code to rotate the gameObject.
private Vector3 mousePoint3D; mousePoint3D = Camera.main.ScreenToWorldPoint(Input.mousePosition + Vector3.back * Camera.main.transform.position.z); transform.LookAt(mousePoint3D, Vector3.back);
If you have an app where you will need to instantiate a gameobject as a child of another gameobject, then you will need to use Transform.SetParent to do this. Unity actually does a nice document on explaining this here. But in case you don’t want to link through, here is the main bit of the code you need.
define your child which is a game object and the transform of the desired parent gameobject clip
public GameObject child; public Transform parent;
Then you assign/remove the child and parent in the following ways
// Sets "newParent" as the new parent of the child GameObject. child.transform.SetParent(newParent); // Same as above, except worldPositionStays set to false // makes the child keep its local orientation rather than // its global orientation. child.transform.SetParent(newParent, false); // Setting the parent to ‘null’ unparents the GameObject // and turns child into a top-level object in the hierarchy child.transform.SetParent(null);
position from world space to local space.