0

So I have this code ( I know there are better ways to do this but I just have one thing in mind) Let's say I have this:

void Update(){

transform.position += transform.forward*2f*Time.deltaTime;


}

This works perfectly fine but if I get a reference to this, it does not work. for example

Vector3 _objPosition;

void Start(){
_objPosition = this.gameObject.transform.position;
}

void Update(){

_objPosition += transform.forward*2f*Time.deltaTime;
}

And this does not work so my question is why can't we get a reference to an object's position, scale, rotation like other components but instead we can only get the value? which why the first code above works but the one below does not

IamBugsy
  • 48
  • 7
  • In the one you think is a reference you do not show ever updatingthe _objreference therefore it retains it original value – BugFinder Nov 27 '20 at 08:13

2 Answers2

1

This is the difference between "reference types" and "value types". The Vector3 is a struct, and by definition, is a value type.

Take 1 for example. It's just a value. It doesn't reference anything. But, if you had an address like 123 Maple Street, that's a reference, and you'd know what to do with an address.

While this is a Unity related question, this is very much a C# (in this case) issue.

This has been answered here. Jon Skeet will sum it up much nicer than I would.

Milan Egon Votrubec
  • 3,696
  • 2
  • 10
  • 24
-1

All variables are passed by value, no matter what. Because of this, you cannot store the reference of this.gameObject.transform.position in the variable _objPosition.

Hedgy
  • 354
  • 1
  • 3
  • 16