在 Unity 中,如何将值从一个脚本传递到另一个脚本? [英] In Unity, how can I pass values from one script to another?

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

问题描述

在 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 GameObject MyObject

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

在其他课程中,您可以:

In other classes you can do:

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 的每个类中定义一个 SpeedController 成员,并通过在 Unity 编辑器中拖放设置引用.然后保存查找,但如果在许多类中需要,这当然很不方便.

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.

另一种方法是创建一个单例,它保存 speed 变量并具有:

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

<小时>

正如 Jan Dvorak 在评论部分所述:


As Jan Dvorak stated in comments section:

public class SpeedController : MonoBehaviour
    public static float speed;

<小时>

[更新]感谢杰达克.是的 Component.SendMessage 绝对应该在列表中:


[Update] Thanks to Jerdak. Yes Component.SendMessage should be definitely on the list:

go.SendMessage("GetFallingSpeed");

同样,您需要像第一个解决方案中描述的那样引用 go.

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

这个问题还有更多的解决方案.如果您正在考虑在所有场景中都处于活动状态的游戏对象,您应该查看 Unity 单例管理器类

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 Unity singleton manager classes

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

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