- Home /
Question by
Digital-Phantom · Mar 26, 2015 at 06:20 PM ·
error messagetransform.positionvaluereturnmodify
transform.position related compile error fixed don't understand why ?
Trying to make a simple script to make enemy objects move left and right. Unfortunately getting error message.
script -
using UnityEngine;
using System.Collections;
public class InvaderMoveBasic : MonoBehaviour
{
static bool goLeft = false;
public int speed = 3;
void Start()
{
}
void Update()
{
if(goLeft == true)
{
transform.position.x -= speed * Time.deltaTime;
}
else
{
transform.position.x += speed * Time.deltaTime;
}
}
void OnTriggerEnter (Collider other)
{
if (other.tag == "LeftWall")
{
goLeft = false;
}
else
if (other.tag == "RightWall")
{
goLeft = false;
}
}
}
the error message -
Assets/InvaderMoveBasic.cs(24,35): error CS1612: Cannot modify a value type return value of `UnityEngine.Transform.position'. Consider storing the value in a temporary variable
However when I change the script to this -
void Update()
{
if(goLeft == true)
{
Vector3 TP = transform.position;
TP.x -= speed * Time.deltaTime;
transform.position = TP;
}
else
{
Vector3 TP = transform.position;
TP.x += speed * Time.deltaTime;
transform.position = TP;
}
}
Now things work fine, but I don't see why. The changes seem to do nothing more than add a couple of useless variables.
???
Comment
Best Answer
Answer by JigneshKoradiya · Mar 26, 2015 at 06:36 PM
static bool goLeft = false;
public int speed = 3;
vector3 pos;
void Start()
{
}
void Update()
{
if(goLeft == true)
{
pos=transform.position;
pos.x -= speed * Time.deltaTime;
transform.position=pos;
}
else
{
pos=transform.position;
pos.x += speed * Time.deltaTime;
transform.position=pos;
}
}