在Unity,我怎么能传递值从一个脚本到另一个? [英] In Unity, how can I pass values from one script to another?

查看:1787
本文介绍了在Unity,我怎么能传递值从一个脚本到另一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在团结,我想一个对象有一个下降速度变量,其他所有的对象都可以访问。由于种种原因,我不能使用内置的重力我想要做的。

In Unity, I want one object to have a falling speed variable that all the other objects can access. For various reasons, I can't use the inbuilt gravity for what I'm trying to do.

我怎样才能在一个对象访问变量反复,这样,当它更新我得到更新的变量,从另一个对象?

推荐答案

有几种方法来实现这一目标。

There are several ways to achieve this.

如果您想通过它连接到一个类成分控制的变速为MyObject

If you want the speed variable controlled by a component which is attached to a class MyObject

public class SpeedController : MonoBehaviour
    public float speed;
    // maybe you want restrict this to have read access, then you should use a property instead

在其他类,你可以做:

GameObject go = GameObject.Find ("MyObject");
SpeedController speedController = go.GetComponent <SpeedController> ();
float courrentSpeed = speedController.speed;

请小心,有一个名为myObject的唯一的东西,否则得到搞砸了一个对象。

Take care that there is one object named MyObject only otherwise things get messed up.

另外,您可以定义每个需要访问类 Speed​​Controller 成员速度,并设置通过拖动参考拖放在Unity编辑器。为您节省查找然后但当然,如果需要在很多类,这是pretty不方便。

Alternatively you can define a SpeedController member in every class that needs access to speed and set a reference via drag and drop in Unity editor. You save the lookup then but of course this is pretty inconvenient if needed in many classes.

另一种方式是创造它持有速度变量,并有单:

Another way is to create a singleton which holds the speed variable and have:

public class MyGlobalSpeedController {
    private static MyGlobalSpeedController instance = null;
    public static MyGlobalSpeedController SharedInstance {
        get {
            if (instance == null) {
                instance = new MyGlobalSpeedController ();
            }
            return instance;
        }
    }
    public float speed;
}   

因此​​,所有的类都可以访问此:

So all classes can access this:

float currentSpeed = MyGlobalSpeedController.SharedInstance.speed


由于扬德沃夏克在评论区说:


As Jan Dvorak stated in comments section:

public class SpeedController : MonoBehaviour
    public static float speed;


[更新]
感谢Jerdak。是<一个href=\"http://docs.unity3d.com/Documentation/ScriptReference/Component.SendMessage.html\">Component.SendMessage应该肯定在名单上:

go.SendMessage("GetFallingSpeed");

同样,你需要有一个参考像第一个解决方案描述。

Again you need to have a reference to go like described in the first solution.

有这个问题甚至更多的解决方案。如果你正在考虑,在所有场景活跃游戏对象,你应该看看 Unity3D单管理类

There are even more solutions to this problem. If you are thinking of game objects that are active in all scenes, you should have a look at Unity3D singleton manager classes

这篇关于在Unity,我怎么能传递值从一个脚本到另一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆