- Home /
Problems setting transform.position.z in C# script.
I'm trying to set an empty GameObjects local Z to a distance set by a RayCast Collision. I seem to have everything working... but the correct method to set the Z value. Would love to know the correct way to do this, apparently position.Set isn't getting me there.
using UnityEngine;
using System.Collections;
public class focalPtColDist : MonoBehaviour {
public float distToCol = 0.0f;
public Vector3 posTemp;
public Vector3 hitPosTemp;
RaycastHit focalPtHit = new RaycastHit();
Ray focalPtRay = new Ray();
void Update() {
focalPtRay = Camera.main.ViewportPointToRay(new Vector3(0.5f,0.5f,0.0f));
posTemp = transform.position;
// if (Physics.Raycast(myray, out myhit, 1000.0f) && Input.GetMouseButtonDown(0))
if (Physics.Raycast (focalPtRay, out focalPtHit, 500.0f)) {
print ("We Hit!");
hitPosTemp = focalPtHit.transform.position;
distToCol = Vector3.Distance(hitPosTemp, posTemp);
transform.position.Set(0.0f,0.0f,distToCol);
}
}
}
Answer by cagezero · Apr 26, 2013 at 01:26 AM
transform.position = new Vector3(0,0,distToCol);
@JVaughan To clarify why you are having the problem with your existing method: Transform.position is a property and Vector3 is a struct - unfortunately this means that when you do a .Set() on it, you are setting it on a temporary copy returned by the property's get function which is then immediately discarded.
Thanks guys, this is obviously an important concept and I was having a bit of difficulty groking it. I have the script behaving as I was expecting now.
Glad to help! Since the answer solved your problem, please consider marking it as the correct answer!