public class Example : MonoBehaviour
{
private Transform myTransform;
private Vector3 myPosition;
private void Start()
{
SetInitialReferences();
}
private void Update()
{
Debug.Log(myTransform.position.ToString()); //why does this update constantly?
Debug.Log(myPosition.ToString()); //this doesent update as I expected not like the other one
}
void SetInitialReferences()
{
myTransform = transform; //why is it faster to use myTransform later on than transform?
myPosition = transform.position;
}
If I’m understanding the question, this comes down to the difference between objects and structs.
When you store “transform.position” in myPosition, you actually store a copy of the vector coordinates in the variable, because Vector3 is a struct. When you assign the object “transform” to myTransform, you are actually storing a reference to a transform object, which is just the way C# does things with objects. This way when you access myTransform.position, you are getting the original transform object, and then finding its current position, whereas with myPosition, you are just accessing a copy of the position as it was when you assigned the variable.
Can be tricky to get your head around at first, but C# just handles assigning objects differently to structs and basic data types like int and float.