【问题标题】:What's the best way of using pointers in tween system?在补间系统中使用指针的最佳方法是什么?
【发布时间】:2017-06-22 15:21:26
【问题描述】:

我使用 Unity,我需要创建补间系统,我将向其传递参数并自行控制它。例如:

Tween tween = new Tween( "tween_move_x", 0.0f, 10.0f, 1.5f, someGameObject.transform.position.x );

该代码会自动将值设置为传递的参数:someGameObject.transform.position.x 从 0.0f 到 10.0f 的时间为 1.5 秒。

我是初学者,我不明白我应该在 c# 中使用什么样的指针来完成这项任务。我尝试使用这样的东西:

float *controlledParamValue;

但它说我需要使用不安全和固定的块。我认为将它用于该问题并不是最好的主意。我只想将我的受控ParamValue 链接到 someGameObject.transform.position.x 以便从 Tween 类自动设置其值。我应该在这里使用什么?

【问题讨论】:

  • C# doesn't allow pointers by default,所以这个问题根本上是不合适的。无法维护对 Vector3 的 x 整数占用的内存值的引用。您最好保留对 transform 的引用并使用另一个(或两个)参数来指示您希望仅对其位置的 x 值进行补间。
  • 顺便说一句,如果您正在寻找快速补间系统,我强烈推荐 DOTween。在涉及 C# 脚本时,有一个功能齐全的免费版本。 u3d.as/aZ1

标签: c# pointers unity3d


【解决方案1】:

在 C# 中不需要指针,只需要使用 ref 关键字即可。

例如:

补间类

using UnityEngine;

public class Tween {

    public Tween (ref float tweenFloat, ref Vector3 tweenVector) {
        tweenFloat = 0.7f;
        tweenVector = new Vector3(0.6f, 1, 12.3f);
    }
}

TweenTest 类

using UnityEngine;

public class TweenTest : MonoBehaviour {

    float myFloat = 0;
    Vector3 myVector = Vector3.zero;
    Tween myTween;

    void Start () {
        myTween = new Tween(ref myFloat, ref myVector);     
        Debug.Log(myFloat);
        Debug.Log(myVector);
    }
}

如果将TweenTest 附加到游戏对象并运行场景,输出将是这样的:

0.7
UnityEngine.Debug:Log(Object)

(0.6, 1.0, 12.3)
UnityEngine.Debug:Log(Object)

如您所见,尽管 floatVector3 是值类型,但通过使用 ref 关键字,您传递了对这些变量的引用而不是值(这是传递值类型时的默认行为方法/构造函数的参数)。

这是第一步。

第二步要记住transform.position.x(和yz)只有get的属性,所以你不能直接改变它的值,但是你可以改变position结构作为一个整体。 因此,如果您只需要对结构的 x 组件进行补间,并且您的 Tween 类接受 float 类型:

Vector3 positionVector = transform.position;
myTween = new Tween(*your other parameters*, ref positionVector.x);
transform.position = positionVector;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-23
    • 2013-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多