我想在多个级别显示玩家名称和团队名称。我创建了一个带有单例的游戏对象,该单例调用servidor来加载这些变量。它在第一级工作,但在其他级别工作。游戏对象仍然存在,但不保存PlayerName和TeamName。我怎么能得到它?
这是我的代码:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class GlobalControl2 : MonoBehaviour
{
private static GlobalControl2 instance = null;
private Text PlayerName;
private Text TeamName;
void Awake ()
{
if (instance == null)
{
instance = this;
DontDestroyOnLoad(this.gameObject);
}
else
{
Destroy(this.gameObject);
}
}
public void Start()
{
PlayerName = GameObject.Find ("PlayerName").GetComponent<Text> ();
TeamName = GameObject.Find ("TeamName").GetComponent<Text> ();
new GameSparks.Api.Requests.AccountDetailsRequest ()
.SetDurable(true)
.Send ((response) => {
PlayerName.text = response.DisplayName;
} );
new GameSparks.Api.Requests.GetMyTeamsRequest()
.SetDurable(true)
.Send(teamResp => {
if(!teamResp.HasErrors)
{
foreach(var teams in teamResp.Teams)
{
Debug.Log("Equipo: " + teams.TeamId);
TeamName.text = teams.TeamId;
}
}
} );
}
}
答案 0 :(得分:0)
目前,您正尝试在多个场景中保留场景特定对象
数据类型“Text”是一个统一对象。
尝试使用“String”代替,在下面的示例中,您将看到 PersistentPlayerName 和 PersistentTeamName 将在下一个场景中可用, PlayerName 和 TeamName 不会。这总是多场景单身人士的风险。
请注意,如果PlayerName和TeamName与GlobalControl2(你称之为DontDestroyOnLoad的那个)位于同一个游戏对象上,则不需要这样做
我并不是建议你完全按照下面的方式进行操作,但这应该足以让你走上正确的道路,如果没有,请添加评论,我会进一步解释。
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class GlobalControl2 : MonoBehaviour
{
private static GlobalControl2 instance = null;
private string PersistentPlayerName;
private string PersistentTeamName;
private Text PlayerName;
private Text TeamName;
void Awake ()
{
if (instance == null)
{
instance = this;
DontDestroyOnLoad(this.gameObject);
}
else
{
Destroy(this.gameObject);
}
}
public void Start()
{
PlayerName = GameObject.Find ("PlayerName").GetComponent<Text> ();
TeamName = GameObject.Find ("TeamName").GetComponent<Text> ();
new GameSparks.Api.Requests.AccountDetailsRequest ()
.SetDurable(true)
.Send ((response) => {
PlayerName.text = PersistentPlayerName = response.DisplayName;
} );
new GameSparks.Api.Requests.GetMyTeamsRequest()
.SetDurable(true)
.Send(teamResp => {
if(!teamResp.HasErrors)
{
foreach(var teams in teamResp.Teams)
{
Debug.Log("Equipo: " + teams.TeamId);
TeamName.text = PersistentTeamName = teams.TeamId;
}
}
} );
}
}