I’m pretty new to programming in general and I’ve come across an issue that is driving me crazy. Let me include my code below.
private var pathToPoint : Transform;
private var targetOffsetTransform : Transform;
function Start () {
pathToPoint = transform;
targetOffsetTransform = transform;
print("targetOffsetTransform.transform.position=" + targetOffsetTransform.transform.position);
pathToPoint.position = Vector3(0,0,0);
print("targetOffsetTransform.transform.position=" + targetOffsetTransform.transform.position);
}
The print statements end up looking something like:
targetOffsetTransform.transform.position=(165.7, 0.2, 167.5)
targetOffsetTransform.transform.position=(0.0, 0.0, 0.0)
My problem is that if I change either var, they both change.
How do I initialize these Transform vars with a value that allows me to do math later and not have them be considered Void, and not have them equal any other var that also needs a transform?
Thanks!
I’m no java scripter but this code will not work because your variables overwrite themself with this lines:
private var pathToPoint : Transform;
private var targetOffsetTransform : Transform;
pathToPoint = transform;
targetOffsetTransform = transform;
Transform is an object thus assignment is by reference. You probably want to use Vector3s as they’re structs and assigned by value (they’re copied, just like other primitive variables such as int, float etc).
For more info, see here:
That’s for C#, but Unity uses Mono under the hood so C# .NET docs from Microsoft usually apply for base language level stuff as Mono is jsut a crossplatform version of .NET.
If you think about it, It would be a performance, memory and logical nightmare if simply assigning var foo = transform; would copy all of the transform object’s values, how would it make a copy of transform,gameobject? You’d end up with two GameObjects in Unity’s scene hierarchy every time you assigned a transform value if it did that!
The reason I’m using Transforms is because I’m doing Quaternion math and it’s using transform variables. I guess I could look into converting all of it to use Vector3, but I’m not sure that’s gonna work.
Not knowing the difference between value and reference assignments I’d suggest you stay away from Quaternion’s for now and use EulerAngles instead.