- Home /
how to communicate with the target gameobject?
I am trying my camera to follow a 2d player only on x position but c# is very strict
this is the script of my camera
public class Follow : MonoBehaviour {
public Transform target;
// Update is called once per frame
void Update () {
transform.position.x = target.position.x;
}
}
I dont know the data type to make store them as a variable, I tried vector but it cant be explicitly convert from float? an explanation as to why this code won't work and why your code would work is a big help. thank you
Answer by robertbu · Mar 05, 2014 at 07:40 PM
Transform.position is a Vector3, and C# is a stickler about how you modify an a single component of transform.position. You can do it this way:
void Update () {
Vector3 pos = transform.position;
pos.x = target.position.x;
transform.position = pos;
}
Answer by unityfanboy · Mar 05, 2014 at 08:19 PM
void Update () {
Vector3 pos = transform.position;
pos.x = target.position.x;
transform.position.x = pos;
}
I dont know why but this did not work, I got 2 errors
Assets/Follow.cs(13,27): error CS1612: Cannot modify a value type return value of UnityEngine.Transform.position'. Consider storing the value in a temporary variable* and *Assets/Follow.cs(13,36): error CS0029: Cannot implicitly convert type
UnityEngine.Vector3' to `float'
I caught my error, but apparently you'd already read the answer. Look at the last code line:
transform.position = pos;
omg it works! its so amazing. thank you so much robertu you really helped me a lot! :D