How to sync Class in Multiplayer

Hello. I have problem that i need Synced Class. Not Struct. Because in my project i don’t want to create everytime copy of my Struct data. It make thinks very hard.

Errors what i get:
UNetWeaver error: The class Character has no default constructor or it’s private, aborting.
UNetWeaver error: GetReadFunc unable to generate function for:Character
UNetWeaver error: GenerateDeserialization for allCompanys unknown type [Character]. UNet [SyncVar] member variables must be basic types.

I get error when i try to use Classes. Here is my Class:

public class Character {
    public string myName;
    public int myAge;
    public float myValue;

    public Character(string tmpName, int tmpAge, float tmpValue)
    {
        this.myName = tmpName;
        this.myAge = tmpAge;
        this.myValue = tmpValue;
    }
    public void AddSomething(float howMuch)
    {
        this.myValue += howMuch;
    }
}

Then here is my CreateGame scripts:

public class CreateGame : NetworkBehaviour
{
    public List<Character> _allCharacters = new List<Character>();
	public void RunGameStarter()
	{
		public List<Character> _allCharacters = new List<Character>();
	 
		Character tmpCharacter = new Character("Random_1", 20, UnityEngine.Random.Range(20, 500));
		_allCharacters.Add(tmpCharacter);
	 
		tmpCharacter = new Character("Random_2", 20, UnityEngine.Random.Range(20, 500));
		_allCharacters.Add(tmpCharacter);
	}
}

When i do this all game makes me that error what you see above.

When i change Class to Struct everything works if i make start like this:

    public class allCharacter : SyncListStruct<Character> { };
    [SyncVar] public allCharacter _allCharacter = new allCharacter();

Is Struct only possible way to do this because Class make that error. But i don’t like a Struct because i change those data all the time in different functions and copy of original data makes everything very hard.

The error tells you what the problem is.

It looks like some other code is trying to instantiate the classes you gave it but and it doesn’t know how to because you have specified a parametered constructor on the class.


When you do that it doesn’t create a default constructor (i.e. one without parameters) by default.


Try adding a constructor with no parameters explicitly even if it has an empty body. i.e.

 public Character() {  }