【发布时间】:2014-05-20 14:06:05
【问题描述】:
例如,我在脚本“HealthBarGUI1”中有一个变量(public static float currentLife),我想在另一个脚本中使用这个变量。 如何将变量从一个脚本传递到另一个 C# Unity 2D?
【问题讨论】:
例如,我在脚本“HealthBarGUI1”中有一个变量(public static float currentLife),我想在另一个脚本中使用这个变量。 如何将变量从一个脚本传递到另一个 C# Unity 2D?
【问题讨论】:
您可以通过以下方式访问它:
HealthBarGUI1.currentLife
我假设 HealthBarGUI1 是您的 MonoBehaviour 脚本的名称。
如果您的变量不是静态的并且 2 个脚本位于同一个 GameObject 上,您可以执行以下操作:
gameObject.GetComponent<HealthBarGUI1>().varname;
【讨论】:
您可以这样做,因为 currentLife 与玩家的关系比与 gui 的关系更密切:
class Player {
private int currentLife = 100;
public int CurrentLife {
get { return currentLife; }
set { currentLife = value; }
}
}
您的 HealthBar 可以通过两种方式访问 currentLife。
1) 使用 GameObject 类型的公共变量,您只需将播放器从层次结构拖放到检查器中脚本组件的新字段中。
class HealthBarGUI1 {
public GameObject player;
private Player playerScript;
void Start() {
playerScript = (Player)player.GetComponent(typeof(Player));
Debug.Log(playerscript.CurrentLife);
}
}
2) 自动方式是通过使用find来实现的。速度有点慢,但如果不经常使用,没关系。
class HealthBarGUI1 {
private Player player;
void Start() {
player = (Player)GameObject.Find("NameOfYourPlayerObject").GetComponent(typeof(Player));
Debug.Log(player.CurrentLife);
}
}
我不会将你的玩家或任何其他生物的 currentLife 变量设为静态。这意味着,此类对象的所有实例共享相同的 currentLife。不过我猜他们都有自己的生命价值吧?
出于安全和简单的原因,在面向对象中,大多数变量应该是私有的。然后可以通过使用 getter 和 setter 方法来访问它们。
我上面那句话的意思是,你也想以一种非常自然的方式在 oop 中对事物进行分组。玩家有生命值吗?写入播放器类!之后,您可以使其他对象可以访问该值。
来源:
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
【讨论】:
//Drag your object that includes the HealthBarGUI1 script to yourSceondObject place in the inspector.
public GameObject yourSecondObject;
class yourScript{
//Declare your var and set it to your var from the second script.
float Name = yourSecondObject.GetComponent<HealthBarGUI1>().currentLife;
}
【讨论】:
试试这个!
//Drag your object that includes the HealthBarGUI1 script to yourSceondObject place in the inspector.
public GameObject yourSecondObject;
class yourScript{
//Declare your var and set it to your var from the second script.
float Name = yourSecondObject.GetComponent<HealthBarGUI1>().currentLife;
【讨论】: