如何将变量从一个脚本传递到另一个C#Unity 2D?
例如,我在脚本"HealthBarGUI1"中有一个变量(公共静态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类型的公共变量,您只需将Player从层次结构"拖放到检查器中脚本组件的新字段中即可.
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.
我的最上面一句话是,您还希望以一种非常自然的方式将事物分组.玩家有生命价值吗?写进球员课!之后,您可以使该值可用于其他对象.
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=46ZjAwBF2T8 http://docs.unity3d.com/Documentation/ScriptReference/GameObject.Find.html http://docs.unity3d.com/Documentation/ScriptReference/GameObject.GetComponent.html