在Unity中同步Text对象

时间:2018-05-17 09:02:00

标签: unity3d

我有一个预制件,上面有一个文本对象,该文本代表预制寿命的计数器,每秒钟都会增加。该脚本在人类与计算机模式下工作正常,但是当我尝试创建主机客户端时,客户端的数字总是不同的。如何让显示在它们上面的数字同步?

public class Timer : MonoBehaviour
{

public Planet pl;


private bool hasDone = false;

public int timeleft =6;
public Text countdownText;

// Use this for initialization
void Start()
{
    timeleft = Random.Range (0, 31);
}
// Update is called once per frame
void Update()
{
    countdownText.text = ("" + timeleft);
    if (pl.get_owner () != null && hasDone == false) {
        StartCoroutine("LoseTime");
        hasDone = true;
    }

    if (pl.get_owner () == "Human") {
        countdownText.color = new Color (0f, 0.5f, 1f, 1f);
    }
    if (pl.get_owner () == "Computer") {
        countdownText.color = new Color (1f, 0.5f, 0f, 1f);
    }

    if (pl.get_collision () > 0) {
        timeleft -= 1;
        pl.decrease_collision ();
    }
}
IEnumerator LoseTime()
{
    if (pl.get_owner () != null) {
        while (true)
        {
            yield return new WaitForSeconds(1);
            timeleft++;
        }
    }
}
}

1 个答案:

答案 0 :(得分:0)

我认为您正在寻找syncvar属性:database screenshot

[SyncVar]
public int timeleft =6;

此外,只有服务器应更改该值。将以下代码添加到您将更改timeleft的所有位置。

if (!isServer)
    return;