Home > Software design >  Why does the value not change when I define a single call?
Why does the value not change when I define a single call?

Time:05-04

Why does the value not change when I define a single call?

if (Input.touchCount == 1)
    {
       Touch screentouch = Input.GetTouch(0);
       var j1 = joint1.transform.position;
       var j2 = joint2.transform.position;
       if (screentouch.phase == TouchPhase.Moved)
       {
         if (distance)
         {
            j1 = j2; // no work???
         }
        }
       }

but I use below one is find.

       j1 = j2; replace to
       joint1.transform.position = joint2.transform.position; is ok
         

what can i do , if i want to use var j1 to replace long joint1.transform.position; Thanks

CodePudding user response:

The problem is that you're not applying the assignment. When you call:

var j1 = joint1.transform.position;
var j2 = joint2.transform.position;

you're getting the current positions for joint1 and joint2. When you assign j1 = j2, you're just changing the Vector3 value for j1, you're not actually changing the position.

If you're wanting joint1 to actually move then you need to set its position:

joint1.transform.position = j1;

CodePudding user response:

Changing a variable a can change another variable b only when b is referenced to a.

This is possible in C

int x = 10;
int &ref = x // ref is referenced to x

ref = 20; // ref is assigned a new value and hence x is also modified

cout << x; // prints 20

There is no solution for this in C#, as using pointers or references (if exist) in C# is considered unsafe. Even if you try to use pointers in C#, you get an error saying:

error CS0214: Pointers and fixed size buffers may only be used in an unsafe context

However, in your question, to update joint1.transform.position, as you can't use references in C#, you can just write

joint1.transform.position = j2 // assigns joint2.transform.position to joint1.transform.position
  • Related