我有一个Player
课程,用于存储玩家的信息。
public class Player {
private string player_id;
public static void NewPlayer(string name) {
Debug.Log("NewPlayer");
Player p = new Player();
p.player_id = "123";
p.register();
}
private void register() {
WWWForm form = new WWWForm();
form.AddField("mode", "register");
form.AddField("player_id", this.player_id);
NetworkManager nm = NetworkManager.instance;
nm.OnFinish += HandleOnFinish;
nm.Push (new NetworkManager.Request(NetworkManager.API_URL, HandleFinishNetwork, form));
nm.Execute();
}
void HandleFinishNetwork(WWW www) {
if(www.text == "OK") {
Debug.Log("Registration OK");
// *** what should I put here to return the Player object to the scene? ***
} else {
Debug.Log("Unexpected Data Returned: " + www.text);
}
}
}
其中NetworkManager
是一个扩展MonoBehaviour
和System.IDisposable
的类。当NetworkManager
完成网络操作后,它会在OnFinish
课程中调用Player
个事件。
我有一个Unity场景,它有一个触发Player.NewPlayer("MyName")
的GUI按钮。当注册正常时,如何将Player
对象返回到场景?
答案 0 :(得分:2)
这取决于你将如何处理播放器或者你将如何操作它,但一个好的通用解决方案是使用委托在播放器注册时执行,如下所示:
public class Player {
private string player_id;
private Action<Player> onPlayerRegistered;
public static void NewPlayer(string name, Action<Player> onPlayerRegistered) {
Debug.Log("NewPlayer");
Player p = new Player();
p.player_id = "123";
p.onPlayerRegistered = onPlayerRegistered;
p.register();
}
// ...
void HandleFinishNetwork(WWW www) {
if(www.text == "OK") {
Debug.Log("Registration OK");
onPlayerRegistered(this);
} else {
Debug.Log("Unexpected Data Returned: " + www.text);
}
}
}
在将要创建播放器的课程中,您可以执行以下操作:
public class SomeClass : MonoBehaviour {
private void Start() {
Player.NewPlayer("Steve Woz", StartTheGame);
}
private void StartTheGame(Player player) {
StopTheSpiningWheel();
ReallyStart(player);
Whatever();
}
甚至:
public class SomeClass : MonoBehaviour {
private void Start() {
Player.NewPlayer("Steve Woz", (player) => { Debug.Log("My name is " + player.name); });
}
所以,这个想法是传递需要玩家在有玩家时执行的方法(也就是说,当它被注册时)。我的例子使用了方便的Action class,最后一段代码使用lambda expression,如果你有一个足够简单的代码可以运行,那么这通常是一个好主意。
最后,看一下描述观察者设计模式的this reference,以获得完整而无聊的解释。