示例我有类名“PlayerClass”和“StatClass”
public float health = 100 ;
public float experience;
PlayerClass playerclass = new PlayerClass()
public float health2;
public float experience2;
health2 = playerclass.health;
experience2 = playerclas.experience;
通常我必须创建“PlayerClass playerclass = new PlayerClass()”
结果将是相同的health2和experience2; 但每当我使用代码对玩家类进行改变时,来自StatClass的结果healt2将与100相同
Sory因为我的英语不好。
-----------------编辑-----
public class GameControl : MonoBehaviour {
public static GameControl control;
public float health = 100;
public float experience = 1000;
// Use this for initialization
void Awake () {
/*
* Awake Start Before Start() Happen
*/
if (control == null) {
DontDestroyOnLoad (gameObject);
control = this;
} else if (control != this) {
Destroy (gameObject);
}
}
}
public class GetHealth : MonoBehaviour {
public static GetHealth getHealth;
GameControl gameControl = new GameControl();
//GameControl gameControl;
public static float health;
Text text;
void Awake () {
/*
* Awake Start Before Start() Happen
*/
if (getHealth == null) {
DontDestroyOnLoad (gameObject);
getHealth = this;
} else if (getHealth != this) {
Destroy (gameObject);
}
text = GetComponent<Text> ();
health = 0;
}
void Update(){
health = gameControl.health;
text.text = "Health: " + health;
}
}
我在GameControl中对值变量Health进行了更改。但是,当变量GameControl没有改变时,Get Health总是与第一次访问100相同。我想这可能是因为我们在GetHealth课上使用“new”。
GameControl gameControl = new GameControl();
有没有另外一种方法可以在没有“新”的情况下解决这个问题。
答案 0 :(得分:1)
如果播放器的实例化在updateStat
方法中且它正在调用void update()
方法,则会导致一次又一次地实例化播放器对象。您可以在构造函数中尝试此操作或实例化playerclass2
。如果只有玩家对象存在,那么健康和体验static
也会有所帮助。
Class StatClass{
PlayerClass playerclass2;
public float health2;
public float experience2;
public void updateStat(){
if(playerclass2==null) playerclass2 = new PlayerClass();
health2 = playerclass2.health;
experience2 = playerclas2.experience;
}
}
修改强>
您不能使用新关键字,因为它来自MonoBehavior
。必须使用ClassName.method()
格式从MonoBehavior
答案 1 :(得分:1)
谢谢大家,我找到了。
只需要
health = GameControl.control.health;
我不必实例化它我只是调用类然后初始化类,然后是类的变量。