【问题标题】:Why does the value not change when I define a single call?为什么定义单个调用时值不会改变?
【发布时间】:2022-07-05 12:59:43
【问题描述】:

为什么定义单个调用时值没有变化?

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???
         }
        }
       }

但我用下面的一个是find。

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

如果我想用 var j1 替换 long joint1.transform.position; 我该怎么办? 谢谢

【问题讨论】:

  • 你想达到什么目的? j1 是一个引用,所以 j1 = j2 只是改变引用,而不是值
  • 你的代码不完整;很难理解您要达到的目标...请添加一个最小的可重现代码 sn-p 并清楚说明您的目标是什么

标签: c# unity3d


【解决方案1】:

问题在于您没有应用作业。当你打电话时:

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

您将获得joint1joint2 的当前位置。当您分配j1 = j2 时,您只是更改了j1Vector3 值,实际上并没有更改位置。

如果您想让joint1 实际移动,那么您需要设置它的位置:

joint1.transform.position = j1;

【讨论】:

    【解决方案2】:

    仅当ba 引用时,更改变量a 才能更改另一个变量b

    这在 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
    

    在 C# 中没有解决方案,因为在 C# 中使用指针或引用(如果存在)被认为是不安全的。即使您尝试在 C# 中使用指针,您也会收到一条错误消息:

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

    但是,在你的问题中,要更新joint1.transform.position,因为你不能在 C# 中使用引用,你可以写

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-21
      • 2016-06-02
      • 2014-11-15
      • 1970-01-01
      • 2010-12-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多