- Home /
I want to teleport my player to a random(from these 4) spot on the x axis, but it doesn't work.
private float[] x = {-8, -4, 4, 8};
private float y = 1;
private float z = 0;
Vector3 NewPos;
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Door"))
{
Vector3 tempPos = transform.position;
int mynum = Random.Range(0, x.Length);
NewPos = new Vector3(x[mynum], y, z);
tempPos.x = NewPos.x;
tempPos.y = NewPos.y;
tempPos.z = NewPos.z;
}
Answer by TreyH · Sep 19, 2018 at 06:38 PM
Be sure to look up the difference between *reference* types and *value* types. Your code can be corrected and simplified to:
Vector3 tempPos = transform.position;
int mynum = Random.Range(0, x.Length);
transform.position = new Vector3(x[mynum], tempPos.y , tempPos.z);
For future reference, Vector3 is a struct, not a class. As a result, when you do something like:
Vector3 tempPos = transform.position;
it might seem like you're going to change the position by changing tempPos
, you're actually changing a copy of that position -- not the position itself. To change position itself, reassign your altered copy back as your transform's position.
Answer by LCStark · Sep 19, 2018 at 06:40 PM
You set the tempPos
value to your transform.position
, but after you modify the tempPos
value you don't change the actual transform position (transform.position = tempPos
).
Answer by kevojo · Sep 19, 2018 at 08:28 PM
not sure what you're trying to do here, but you never actually are telling the transform to change anything. You are telling another number "TempPos" to adopt your current position, but you aren't telling your current position to adopt a different value. I don't even understand why you are using a TempPos. You could just set your new value all in one statement.
if ('conditions')
{
transform.position = new Vector3(x[Random.Range(0, x.length)], transform.position.y, transform.position.z);
}
it's worth noting that 'Random.Range' is inclusive of lowest value, and exclusive of highest value - you've used it correctly here but it's something a lot of people don't know apparently that can trip them up.
Another thing worth mentioning.... I find your naming conventions disturbing... hope this helps, Cheers!