- Home /
Need some help with to grap .x with a Raycasthit (c#)
Hi
Im very new to Unity3d, so im hopping some of you elite users can help me..
Im trying to move and cube on the x-axis to where you click/point.
the issue im having and from what i can read c# has an issue with x,y,z and Vector3, but im not sure how to do it right.
using UnityEngine;
using System.Collections;
public class Mover : MonoBehaviour {
private Ray ray;
private RaycastHit hit;
void Start (){
}
void Update (){
if(Input.GetMouseButton(0))
{
ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if(Physics.Raycast(ray, out hit))
{
transform.position.x = hit.point.x;
}
}
}
}
Thanks, Smus
Answer by Statement · Dec 16, 2012 at 11:44 PM
Vector3 tmp = transform.position;
tmp.x = hit.point.x;
transform.position = tmp;
Specifically the issue you refer to is that Vector3 is a value type, which means it's passed by value and not by reference (all its members gets copied into a new variable). Typically if you would be accessing a field then no copy has to be performed, but Transform.position is a property which gives you a copy of the value. This means that it would make no sense to modify x of the value returned, since it is a copy of the value it stores, and any changes to it would be discarded. UnityScript does not have this "issue". The language creates the temporary value under the hood for you but in C# you have to be more explicit about it.
So the way to do it is to get the copy as a temp variable, modify the temp and then store the temp back into Transform.position, as shown above.