c# - 在游戏对象上运行一次脚本

标签 c# unity3d

我有一个脚本,它使用 Unity 引擎的 lerp 功能处理游戏对象随时间的转换。

public class MovePiece : MonoBehaviour {
    Vector3 startPoint;
    Vector3 endPoint;
    float speed = 1;
    float startTime;
    float journeyLength;

    void Start() {
        startPoint = gameObject.GetComponent<Transform>().position;
        endPoint = startPoint + new Vector3(20, 0, 0); //Will make this a variable eventually
        startTime = Time.time;
        journeyLength = Vector3.Distance(startPoint, endPoint);
    }

    void Update() {
        float distCovered = (Time.time - startTime) * speed;
        float fracJourney = distCovered / journeyLength;
        transform.position = Vector3.Lerp(startPoint, endPoint, fracJourney);
    }
}

但是,我只希望它在我单击一个游戏对象时运行一次,然后在它完成移动后将其自身与该对象分离,以便下次我单击另一个对象时它可以再次运行。

我有一个连接到相机的光线转换设置,它允许我选择游戏对象,我只是不知道我如何在选定的对象上运行这个脚本!

我该怎么做?

最佳答案

重命名您的 Start 方法

void Start() { ... }

其他组件可以公开访问的内容,即:

public void BeginMove() { ... }

然后,让您的 Raycast 脚本调用您的新函数。您需要访问被单击的游戏对象的 MovePiece 组件:

...
GameObject hitObject = raycastHit.collider.gameObject;
MovePiece hitObjectMovePiece = hitObject.getComponent<MovePiece>();
hitObjectMovePiece.BeginMove();

您可能还想在动画中引入 bool 锁。您的代码可能如下所示。

    public class MovePiece : MonoBehaviour {
    Vector3 startPoint;
    Vector3 endPoint;
    float speed = 1;
    float startTime;
    float journeyLength;

    // Animation lock
    private bool moving = false;

    public void BeginMove() {
        startPoint = gameObject.GetComponent<Transform>().position;
        endPoint = startPoint + new Vector3(20, 0, 0); //Will make this a variable eventually
        startTime = Time.time;
        journeyLength = Vector3.Distance(startPoint, endPoint);

        moving = true;
    }

    void Update() {
        if(!moving)
            return;

        float distCovered = (Time.time - startTime) * speed;
        float fracJourney = distCovered / journeyLength;
        transform.position = Vector3.Lerp(startPoint, endPoint, fracJourney);

        if(fracJourney >= 1.0f)
            moving = false;
    }
}

希望对您有所帮助!祝你好运。

关于c# - 在游戏对象上运行一次脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33754327/

相关文章:

c# - 将 Decimal 数组转换为 Double 数组

c# - 我是否在我的一个页面中滥用了 WebMatrix 的 AntiForgery.Validate 助手?

c# - MVP 中的接口(interface)和类

c# - 如何将 float 转换为 int?

c# - 无法更改实例化游戏对象的 transform.position

c# - ASP.NET 成员身份按用户角色重定向到页面

c# - 如果我的函数在处理时失败,System.MessageQueue (MSMQ) 消息是否会丢失?

unity3d - 寻找线段-矩形交点

c# - 如何让 LookAt 对齐 transform.up 向量而不是 transform.forward?

c# - 为什么 Unity 在 Mono 支持 .NET 3.5 时使用 .NET 2.0?