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;
    		}
		}
    }

1 Answer

1

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 MoveOnZ(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.MoveOnZ(0.7f);

Thank you for that. I couldn't figure out why it wasn't working.

Also, should have caught this in the beginning, but if you intend to do this for each individual key press, and not while holding the key, you should change GetKey() to GetKeyDown().

You can also use the built in Transform.Translate() method, which accomplishes this as well.

How do you do it with transform.translate? I tried using transform.translate originally but I was getting the same error I was here.