- Home /
C# Teleport Script Error
Hi everyone, I'm trying to make a script where the player is teleported +0.7 in the z axis each time the key T is pressed. But I get this error Cannot modify a value type return value of 'UnityEngine.Transform.positon'.Any idea how to fix this?
using UnityEngine;
using System.Collections;
public class Teleport : MonoBehaviour
{
void Update(){
if (Input.GetKey(KeyCode.T)){
transform.position.z += 0.7;
}
}
}
Answer by iwaldrop · Apr 19, 2013 at 04:52 AM
You can't modify the axes directly. Instead, do this:
Vector3 position = transform.position;
position.z += 0.7f;
transform.position = position;
Because this is a bit of a pain to do every time you want to manipulate axis values, you could make methods that extend Transform to do the work for you:
public static class TransformExtensions
{
public static void $$anonymous$$oveOnZ(this Transform t, float amount)
{
Vector3 p = t.position;
p.z += amount;
t.position = p;
}
}
Then to use that method you'd just call transform.$$anonymous$$oveOnZ(0.7f);
Thank you for that. I couldn't figure out why it wasn't working.
You can also use the built in Transform.Translate() method, which accomplishes this as well.
@DangerousBeans: This is necessary because .position / .localPosition / ... are properties and not variables. To change the value of a property you have to assign something to it. You just "read" it and change a member of the temporal copy which won't affect the value of the property.
Properties are just methods. When you do
transform.position.x += 1;
It's just short for
transform.position.x = transform.position.x + 1;
Since position is a property you only call get get-method here. So it actually looks like that:
transform.get_Position().x = transform.get_Position().x + 1;
get_Position() will return a copy of the Vector3 and you set the x value of it, but only on the copy.
When you do this ins$$anonymous$$d:
transform.position = transform.position + Vector3.forward;
you actually do:
transform.set_Position(transform.get_Position() + Vector3.forward);
Which will work since you invoke the setter.