1

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

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();
    }
}
4

1 回答 1

2

只需在方法的开头添加以下内容Start()

if (!isServer)
{
    return;
}

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

于 2018-07-02T13:30:15.933 回答