- Home /
Unet: Best way to Sync multiple variables
I'm pretty new to Unet and Networking. The biggest issue I'm currenlty running into is syncing my stuff to both Host(Server) and Client. Every time I think I know how it works, it just doesn't work like I expected.
I know I have to send something to the server with a [Command] and than sync it with a [SyncVar]. But this doesn't always work or is just to much if you have to sync multiple variables.
private float InputAxis;
[SyncVar (hook = "PlayerSpriteCallback")]
public SpriteRenderer PlayerSprite;
[SyncVar (hook = "ToolSpriteCallback")]
public SpriteRenderer ToolSprite;
[SyncVar (hook = "HandSpriteCallback")]
public SpriteRenderer HandSprite;
void Update ()
{
if(isLocalPlayer)
{
InputAxis = Input.GetAxis("Horizontal");
if(InputAxis > 0)
{
CmdDirectionChange(1);
}
else if(InputAxis < 0)
{
CmdDirectionChange(-1);
}
}
}
[Command]
void CmdDirectionChange(int direction)
{
if(direction == 1) // Right
{
// un-flip the player sprite.
PlayerSprite.flipX = false;
HandSprite.sortingOrder = 2; // Above Player, above tool.
ToolSprite.sortingOrder = 1; // Above Player, behind hand.
}
else if (direction == -1) // Left
{
// Flip the player sprite.
PlayerSprite.flipX = true;
HandSprite.sortingOrder = -1; // Behind Player above tool.
ToolSprite.sortingOrder = -2; // Behind Player and hand.
}
}
void PlayerSpriteCallback(SpriteRenderer sprite)
{
PlayerSprite = sprite;
}
void ToolSpriteCallback(SpriteRenderer sprite)
{
ToolSprite = sprite;
}
void HandSpriteCallback(SpriteRenderer sprite)
{
HandSprite = sprite;
}
This code only works on the Host (Server) and not on the Client player (I do have Local Player Authority selected). What am I doing wrong? Is it because I try to sync entire spriteRenderers? If so does that mean I have to sync every bool, int ect. in the direction change function? What if I have even more values I have to sync in the future, doesn't that end up in a gigantic mess eventually?
I think SpriteRenderer data type can not be used as SyncVars. Only primitive data types like int,float,txt field can be used as shyncvars.
Hmm.. I guess that was expected. I just keep on thinking about how I could do this most efficiently (also for future usage). $$anonymous$$aking a syncvar for every value I want to sync sounds very messy and unefficient.
Just in case you don't know yet there is also SyncListint, SyncListbool etc. If you want to sync a list of custom objects you can use SyncListstruct. I am also currently trying to get this work.
Your answer
Follow this Question
Related Questions
SyncVar works with disabled components? 0 Answers
Unet Instantiate 0 Answers
UNET 5.3 Shooting Client/Server Sync issue 0 Answers
[UNET] TRANSFORMATION NOT SYNCING 0 Answers
Networking Sync SetActive Not Working 0 Answers