在UnityNetwork中同步随机数

时间:2018-07-02 11:22:06

标签: c# unity3d unet

我想为服务器启动时产生的对象分配随机数,但是游戏的每个实例都会生成自己的随机数,并且它们不会同步,我该如何解决?

public class Health : NetworkBehaviour
{
    public Text PlanetHealth;
    public const int maxHealth = 100;

    [SyncVar(hook = "OnChangeHealth")]
    public int currentHealth = maxHealth;


    void Start()
    {
        if(this.gameObject.name == "GrayPlanet(Clone)")
        {
            currentHealth = Random.Range(0, 50);
            PlanetHealth.text = currentHealth.ToString();
        }
        else
            PlanetHealth.text = maxHealth.ToString();
    }

    public void TakeDamage(int amount)
    {
        if (!isServer)
        {
            return;
        }
        currentHealth -= amount;
        if (currentHealth <= 0)
        {
            currentHealth = 55;
        }
    }
    void OnChangeHealth(int currentHealth)
    {
        PlanetHealth.text = currentHealth.ToString();
    }
}

1 个答案:

答案 0 :(得分:2)

只需将其添加到您的Start()方法的开头:

if (!isServer)
{
    return;
}

您应该只在服务器端进行随机生成。之后,SyncVar将执行使实例保持最新状态的工作。