簡體   English   中英

客戶端無法在服務器上生成 object - Unity 鏡像網絡 c#

[英]Clients cannot spawn object on server - Unity mirror networking c#

我已經為此苦苦掙扎了一兩天了。 由於某種原因 NetworkServer.Spawn() 似乎不起作用。 據我了解,可以從客戶端調用 NetworkServer.Spawn() 以在服務器上生成 object,從服務器上調用 object 在所有客戶端上生成。 目前,當客戶端射擊時,它只出現在該客戶端上(不在服務器上),當主機射擊時,彈丸會在主機和客戶端上生成。

代碼頂部有一個 using Mirror 標簽,該腳本派生自 Networkbehaviour。 下面這段代碼是在客戶端調用的:

void Shoot()
{
        //Spawn porjectile on local machine
        GameObject shot = Instantiate(projectile) as GameObject;

        //Set shot projectile position
        shot.transform.position = projectilePoint.position;
        shot.transform.rotation = transform.rotation;

        //Set projectile component of the shot projectile
        Projectile shotProjectile = shot.GetComponent<Projectile>();

        //Set properties of shot projectile
        shotProjectile.damage = damage;
        shotProjectile.direction = projectilePoint.position - transform.position;
        shotProjectile.speed = projectileTravelSpeed;
        shotProjectile.team = team;
        shotProjectile.shotBy = gameObject;

        NetworkServer.Spawn(shot);
    
}

有誰知道為什么彈丸沒有從客戶端生成在服務器上? 一個代碼示例(在 c# 中)也將非常有幫助。

NetworkServer.Spawn()只能在服務器上調用。 它使GameObject被發送到所有客戶端,因此他們可以看到它,與之交互等等。 因此,您需要從客戶端調用服務器上的 function,這將為您生成Spawn()您的 object。

[Client]
void Shoot()
{
    //Call spawn on server
    CmdShoot(projectile, projectilePoint.position, transform.rotation);
}

[Command]
void CmdShoot(GameObject projectile, Vector3 position, Quaternion rotation)
{

    GameObject shot = Instantiate(projectile) as GameObject;

    //Set shot projectile position
    shot.transform.position = projectilePoint.position;
    shot.transform.rotation = transform.rotation;

    //Set projectile component of the shot projectile
    Projectile shotProjectile = shot.GetComponent<Projectile>();

    //Set properties of shot projectile
    shotProjectile.damage = damage;
    shotProjectile.direction = projectilePoint.position - transform.position;
    shotProjectile.speed = projectileTravelSpeed;
    shotProjectile.team = team;
    shotProjectile.shotBy = gameObject;

    NetworkServer.Spawn(shot);
    RpcOnShoot();
}

[ClientRpc]
void RpcOnShoot()
{
    //Called on all clients
}

或者調用NetworkServer.SpawnWithClientAuthority() ,如果你希望實例化的 object 具有客戶端權限(客戶端需要設置shotProjectiles屬性)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM