如何将变量从一个脚本传递到另一个 C# Unity 2D? [英] How do I pass variable from one script to another C# Unity 2D?

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

问题描述

例如,我在脚本HealthBarGUI1"中有一个变量(public static float currentLife),我想在另一个脚本中使用这个变量.如何将变量从一个脚本传递到另一个 C# Unity 2D?

For example I have a variable (public static float currentLife) in script "HealthBarGUI1" and I want to use this variable in another script. How do I pass variable from one script to another C# Unity 2D?

推荐答案

你可以这样做,因为 currentLife 与玩家的关系比与 gui 的关系更大:

You could do something like this, because currentLife is more related to the player than to the gui:

class Player {

  private int currentLife = 100;

  public int CurrentLife {
    get { return currentLife; }
    set { currentLife = value; }
  }

}

您的 HealthBar 可以通过两种方式访问​​ currentLife.

And your HealthBar could access the currentLife in two ways.

1) 使用 GameObject 类型的公共变量,您只需将玩家从层次结构拖放到检查器中脚本组件的新字段中即可.

1) Use a public variable from type GameObject where you just drag'n'drop your Player from the Hierarchy into the new field on your script component in the inspector.

class HealthBarGUI1 {

  public GameObject player;
  private Player playerScript;

  void Start() {
    playerScript = (Player)player.GetComponent(typeof(Player)); 
    Debug.Log(playerscript.CurrentLife);
  }

}

2)自动方式是通过使用find来实现的.有点慢,但如果不经常使用,没关系.

2) The automatic way is achieved through the use of find. It's a little slower but if not used too often, it's okay.

class HealthBarGUI1 {

  private Player player;

  void Start() {
    player = (Player)GameObject.Find("NameOfYourPlayerObject").GetComponent(typeof(Player));
    Debug.Log(player.CurrentLife);
  }

}

我不会让你的玩家或任何其他生物的 currentLife 变量成为静态的.这意味着,此类对象的所有实例共享相同的 currentLife.但我想他们都有自己的人生价值吧?

I wouldn't make the currentLife variable of your player or any other creature static. That would mean, that all instances of such an object share the same currentLife. But I guess they all have their own life value, right?

在面向对象中,出于安全性和简单性的原因,大多数变量应该是私有的.然后可以通过使用 getter 和 setter 方法访问它们.

In object orientation most variables should be private, for security and simplicity reasons. They can then be made accessible trough the use of getter and setter methods.

我上面这句话的意思是,您还希望以一种非常自然的方式在 oop 中对事物进行分组.玩家有生命值吗?写入播放器类!之后,您可以使其他对象可以访问该值.

What I meant by the top sentence, is that you also would like to group things in oop in a very natural way. The player has a life value? Write into the player class! Afterwards you can make the value accessible for other objects.

来源:

https://www.youtube.com/watch?v=46ZjAwBF2T8http://docs.unity3d.com/Documentation/ScriptReference/GameObject.Find.htmlhttp://docs.unity3d.com/Documentation/ScriptReference/GameObject.GetComponent.html

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

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