Unet:使用客户端权限生成其他对象

时间:2015-11-09 21:08:13

标签: c# unity3d unity5 unity-networking

我正在使用Unity中的新Unet功能制作一个简单的tic tac-tac-tac-toe游戏,以学习如何使用Unet功能。

我有一个脑代码,它会产生9个精灵来构成棋盘,并且正在努力将这些精灵设置为x。我使用[synchvar]跟踪精灵的状态,并使用钩子在[SyncVar]更改时更改图像。如果我控制服务器,游戏将完美运行,但如果我控制客户端则无效。根据我的理解,您可以通过向对象添加本地播放器权限并使用[命令]来更正此问题,但这似乎无法解决问题。下面的代码是我精灵的附件。问题已得到解答,下面的代码反映了纠正。

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine.Networking;


public class spacescript : NetworkBehaviour {
    public Sprite x;
    public Sprite o;
    SpriteRenderer sr;
    public int state;
    NetworkIdentity myNetId;

    void Awake ()
    {

        myNetId = GetComponent<NetworkIdentity>();

    }

    public void setstate(int newstate)
    {
        state=newstate;

        if (state == 1) 
        {
            gameObject.GetComponent<SpriteRenderer> ().sprite = x;
        }
    }

    void OnMouseDown()
    {

        GameObject whatplayer = braincode.singleton.GetComponent<braincode> ().returnplayer();
        whatplayer.GetComponent<playerscript> ().thingwasclicked (myNetId, gameObject);


    }




}

我的图块由以下代码生成

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine.Networking;

public class braincode : NetworkBehaviour {
    public GameObject spaceprefab;
    static public braincode singleton;

    GameObject players;
    public static GameObject brain;
    void Start ()
    {

        singleton = this;
        brain = gameObject;
    }
    public GameObject  returnplayer()
    {
        return players;
    }
    public void add_player(GameObject player)
    {

        players = player;


    }
    public override void OnStartServer()
    {

        for (int x=0; x<3; x++) {
            for (int y=0; y<3; y++) {

                GameObject  space = (GameObject)GameObject.Instantiate(spaceprefab, transform.position, Quaternion.identity);

                space.transform.position = new Vector3 (-3 + (2 * x), -3+ (2*y), 0f);
                NetworkServer.Spawn (space);
            }
        }

    }
}

我的playerobjects有以下代码

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine.Networking;

public class playerscript : NetworkBehaviour {


    void Start () 
    {


        if (isLocalPlayer) 
        {

            braincode.brain.GetComponent<braincode> ().add_player (gameObject);

        }
    }

    public void thingwasclicked(NetworkIdentity tiles , GameObject whoclicked)
    {
        Cmdassignstate (tiles,whoclicked);
    }

    [Command]
    public void Cmdassignstate(NetworkIdentity tile, GameObject whoclicked)

    {

        RpcUpdateState (1,whoclicked);

    }

    [ClientRpc]
    void RpcUpdateState(int newState, GameObject tile)
    {
        tile.GetComponent<spacescript> ().setstate (1);

    }




}

0 个答案:

没有答案