|
| 1 | +# Entity factories |
| 2 | + |
| 3 | +Entity factories allows you to optimize your server performance by defining the data you need to store in a player or vehicle on compile time. This allows much faster data access than via .SetData, ```.GetData```. |
| 4 | + |
| 5 | +## Step 1, Create the class |
| 6 | + |
| 7 | +Defining your custom player or vehicle class by extending ```Player``` or ```Vehicle```. |
| 8 | +You need to implement the default constructor of ```Player``` or ```Vehicle``` as well. |
| 9 | + |
| 10 | +```csharp |
| 11 | +public class MyPlayer : Player |
| 12 | +{ |
| 13 | + public bool LoggedIn { get; set; } |
| 14 | + |
| 15 | + public MyPlayer(IntPtr nativePointer, ushort id) : base(nativePointer, id) |
| 16 | + { |
| 17 | + LoggedIn = false; |
| 18 | + } |
| 19 | +} |
| 20 | +``` |
| 21 | + |
| 22 | +You can't create a player via a constructor, because the player class will be created automatically when someone connects. |
| 23 | +Thats why you need to create a factory that will create the player for you when its needed. |
| 24 | + |
| 25 | +## Step 2, Create the factory |
| 26 | + |
| 27 | +In the factory the defined default constructor of the player or vehicle class will be called. |
| 28 | +You only need to override the ```IPlayer Create(IntPtr playerPointer, ushort id)``` method and initialize your own class instead of the default one. |
| 29 | + |
| 30 | +```csharp |
| 31 | +public class MyPlayerFactory : IEntityFactory<IPlayer> |
| 32 | +{ |
| 33 | + public IPlayer Create(IntPtr playerPointer, ushort id) |
| 34 | + { |
| 35 | + return new MyPlayer(playerPointer, id); |
| 36 | + } |
| 37 | +} |
| 38 | +``` |
| 39 | + |
| 40 | +## Step 3, Apply the factory |
| 41 | + |
| 42 | +Now you need to tell the module that it should use your own entity factory for the player. |
| 43 | +You simply do this by overriding ```IEntityFactory<IPlayer> GetPlayerFactory()``` method in your Resource class. |
| 44 | +This will look like the code below. |
| 45 | + |
| 46 | +```csharp |
| 47 | +public class SampleResource : Resource { |
| 48 | + public override IEntityFactory<IPlayer> GetPlayerFactory() |
| 49 | + { |
| 50 | + return new MyPlayerFactory(); |
| 51 | + } |
| 52 | +} |
| 53 | +``` |
| 54 | + |
| 55 | +This also works when you extend ```AsyncResource``` ect. |
| 56 | + |
| 57 | +It works exactly the same for vehicles. |
0 commit comments