- Home /
Teleporting 2 objects
I am trying to do this part in a code were 2 objects switch places with each other but I am not sure how to do it. Can you please help ?
Answer by Xarbrough · Oct 16, 2015 at 11:47 AM
public Transform myObjectA;
public Transform myObjectB;
private void Start()
{
Vector3 tempPosition = myObjectA.position;
myObjectA.position = myObjectB.position;
myObjectB.position = tempPosition;
}
That's basic swapping, but if you're starting out, you should watch some of the tutorial on the Unity learn site. This one seems to incorporate some of the needed aspects and maybe gives you some inspiration: Teleportation Grenades
Better question: How would you do it without a tempVector? If you change one of the transforms, you lose that information unless you previously store it in a temporary variable.
Yep, you usually need a temp variable. However for simple datatypes (int, byte, ...) you can use "xor" to swap two values without a temp variable:
// C#
int a = 5; // 0101
int b = 3; // 0011
a = a ^ b; // a = 0101^0011 = 0110
b = a ^ b; // b = a ^ b ^ b --> b = a b = 0110^0011 = 0101 (former a)
a = a ^ b; // a = a ^ b ^ a (the new b) --> a = b a = 0110^0101 = 0011 (former b)
It's an old trick the usually isn't worth the hassle.
That's why i love LUA. In lua there are multi-values. A swap in lua looks like this:
// LUA
a,b = b,a
my last question is why is it a vector3 im not really sure how or when i need a vector3 ?
Your answer