How to teleport a specific object to an empty?
I want to whenever I click on a cube to teleport to an empty. I know the OnMouseDown and the transform.position but I don't know how to say to teleport to a specific empty, in C#. Thank you.
Empty gameObject, the one you create with Ctr+Shift+N.
Answer by UltraSage · Apr 23, 2016 at 03:00 PM
Do You mean an empty GameObject, or some empty position?
If You want to teleport the cube just to position of some empty object, then You should first get position of such object. Ex:
GameObject empty;
//declare empty GameObject called "empty"
Vector3 pos;
//declare empty Vector3
void Start () {
empty = GameObject.Find ("Empty");
//Appends actual gameobject called "Empty" to our 'empty' variable we recently declared
pos = empty.transform.position;
//Appends position of the "Empty" gameobject to 'pos' variable we recently decalred
}
//If the "Empty" GameObject is moving, then you should put this into Update() function
void OnMouseDown () {
transform.position = pos;
//"teleports" the object to coordinates in 'pos' variable
}
This will physically "teleport" Your object to any given GameObject called "Empty". You can read up more on it here: http://docs.unity3d.com/ScriptReference/Transform-position.html
If You want to append object as a child to an empty object in hierarchy, then You should use Transform.parent, like this:
void OnMouseDown () {
transform.parent = empty.transform;
//Appends object that bears the script to gameobject tied to 'empty' variable
}
You can read more about it here: http://docs.unity3d.com/ScriptReference/Transform-parent.html
Your answer

Follow this Question
Related Questions
Character Can't Move After Position Change 0 Answers
Player teleport not working 0 Answers
How to teleport game object to another scene at the exact position from previous scene? 0 Answers
How to transform position of one object to the exact position of another object? 0 Answers
OnCollisionEnter/OnControllerColliderHit/onTriggerEnter Won't work as teleporter? 0 Answers