- Home /
Question by
Zignd · Aug 16, 2014 at 06:40 AM ·
c#movementgameobjecttransform
Modifying the Transform of a GameObject
I'm trying to make a simple thing with the Transform component of one of my GameObjects. To do so I added a script to it and added the following code:
using UnityEngine;
using System.Collections;
public class CameraController : MonoBehaviour {
private GameObject gameObject;
public void Start () {
this.gameObject = GameObject.Find("Main Camera");
}
public void Update () {
this.ManageUserInput();
}
private void ManageUserInput()
{
if (Input.GetKey(KeyCode.W))
{
Transform gameObjectTransform = this.gameObject.GetComponent<Transform>();
gameObjectTransform.position = new Vector3(
gameObjectTransform.position.x,
gameObjectTransform.position.y,
gameObjectTransform.position.z - 0.5);
}
}
}
As you can see it's nothing that smart, but I whenever I run it I get the following error:
error CS1612: Cannot modify a value type return value of `UnityEngine.Transform.position'. Consider storing the value in a temporary variable
Can someone explain me why it doesn't work?
Thanks in advance.
Comment
Best Answer
Answer by zharik86 · Aug 16, 2014 at 06:47 AM
Maybe rewrite you function ManageUserInput:
public void ManageUserInput() {
if (Input.GetKey(KeyCode.W)) {
//First this.transform - reference for current transform of object
//Second, for CSharp wrong write value 0.5, change to 0.5f
this.transform.position = new Vector3(this.tranform.position.x,
this.tranform.position.y, this.transform.position.z - 0.5f);
}
}
I hope that it will help you.