Skip to content

Commit

Permalink
Users must initialize syncobjects (#391)
Browse files Browse the repository at this point in the history
Previously we initialized syncobjects, so this is valid:
```cs
public class Pepe : NetworkBehavior {

    public SyncList<int> mylist;
}
```

With this change,  users must initialize their own fields:
```cs
public class Pepe : NetworkBehavior {

    public SyncList<int> mylist = new SyncList<int>();
}
```

BREAKING CHANGE: You must initialize all your SyncLists
  • Loading branch information
paulpach committed Oct 11, 2020
1 parent 9578be0 commit c0e2632
Showing 1 changed file with 0 additions and 39 deletions.
39 changes: 0 additions & 39 deletions Assets/Mirror/Editor/Weaver/Processors/SyncObjectInitializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,49 +8,10 @@ public static class SyncObjectInitializer
{
public static void GenerateSyncObjectInitializer(ILProcessor worker, FieldDefinition fd)
{
// call syncobject constructor
GenerateSyncObjectInstanceInitializer(worker, fd);

// register syncobject in network behaviour
GenerateSyncObjectRegistration(worker, fd);
}

// generates 'SyncList<int> = new SyncList<int>()' if user didn't do that yet
static void GenerateSyncObjectInstanceInitializer(ILProcessor worker, FieldDefinition fd)
{
// check the ctor's instructions for an Stfld op-code for this specific sync list field.
foreach (Instruction ins in worker.Body.Instructions)
{
if (ins.OpCode.Code == Code.Stfld)
{
var field = (FieldDefinition)ins.Operand;
if (field.DeclaringType == fd.DeclaringType && field.Name == fd.Name)
{
// Already initialized by the user in the field definition, e.g:
// public SyncList<int> Foo = new SyncList<int>();
return;
}
}
}

// Not initialized by the user in the field definition, e.g:
// public SyncList<int> Foo;

TypeDefinition fieldType = fd.FieldType.Resolve();
// find ctor with no parameters
MethodDefinition ctor = fieldType.Methods.FirstOrDefault(x => x.Name == ".ctor" && !x.HasParameters);
if (ctor == null)
{
Weaver.Error($"Can not initialize field {fd.Name} because no default constructor was found. Manually initialize the field (call the constructor) or add constructor without Parameter", fd);
return;
}
MethodReference objectConstructor = Weaver.CurrentAssembly.MainModule.ImportReference(ctor);

worker.Append(worker.Create(OpCodes.Ldarg_0));
worker.Append(worker.Create(OpCodes.Newobj, objectConstructor));
worker.Append(worker.Create(OpCodes.Stfld, fd));
}

public static bool ImplementsSyncObject(TypeReference typeRef)
{
try
Expand Down

0 comments on commit c0e2632

Please sign in to comment.