C# 在 Unity 中,如何将值从一个脚本传递到另一个脚本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13891892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:03:29  来源:igfitidea点击:

In Unity, how can I pass values from one script to another?

c#unity3d

提问by Dakeyras

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.

在 Unity 中,我希望一个对象具有所有其他对象都可以访问的下降速度变量。由于各种原因,我无法将内置重力用于我正在尝试做的事情。

How can I access a variable in one object repeatedly, so that when it updates I get the updated variable, from another object?

如何重复访问一个对象中的变量,以便在它更新时从另一个对象获取更新的变量?

采纳答案by Kay

There are several ways to achieve this.

有几种方法可以实现这一点。

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

如果您希望速度变量由附加到游戏对象的组件控制 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;

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

注意只有一个名为 MyObject 的对象,否则事情会变得一团糟。

Alternatively you can define a SpeedControllermember in every class that needs access to speedand 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.

或者,您可以SpeedController在需要访问的每个类中定义一个成员,speed并通过在 Unity 编辑器中拖放来设置引用。然后保存查找,但是如果在许多类中需要,这当然非常不方便。



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

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

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:

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

public class SpeedController : MonoBehaviour
    public static float speed;


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

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

go.SendMessage("GetFallingSpeed");

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

同样,您需要引用go第一个解决方案中描述的类似内容。

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 单例管理器类

回答by Furjoza

If I were you I would just make this speed variable "static public" so you can access it from anywhere. You should always avoid "find.anything" etc functions, they are quite slow. There is no reason for you to look for something that you exactly know where it is.

如果我是你,我会把这个速度变量设为“静态公开”,这样你就可以从任何地方访问它。你应该总是避免“find.anything”等函数,它们很慢。你没有理由去寻找你确切知道它在哪里的东西。

回答by Martin j

other.GetComponent<class name>().object name;

回答by NBAH79

if it is in the fixedUpdate – Martin j

如果它在 fixedUpdate 中 – Martin j

seems like it works well in Awake too. Both scripts are added to the same GameObject.

似乎它在 Awake 中也很有效。两个脚本都添加到同一个游戏对象中。

public class FirstScript : MonoBehaviour {
    protected internal GameObject myobject;
private void Awake() {
       myobject = (GameObject)Instantiate(Resources.Load("nameofprefab"));
       myobject.transform.parent = gameObject.transform;
...
public class SecondScript : MonoBehaviour {
    private GameObject myobject;
private void Awake() {
       myobject = gameObject.GetComponent<FirstScript>().myobject;
       myobject.SetActive(false); //for example
...