jeudi 5 octobre 2017

How to use a 3rd party code without integrating into my own code ? (C#)

I want to use a 3rd party network asset for my Unity3d game.

TL;DR : What is the best solution to use an asset without really integrating the asset code into my own code for this reasons:

  1. The asset is being updated regularly.
  2. Maybe in the future i will want to change that network asset to my own\other solution.

My initial solution was to create an Interface called INetworkProvider which all network solutions will implement, create a class that will drive from the 3rd party class that will handle my requests to that object.

The problem is what happens when the 3rd party asset require a type which my code doesn't know about ? In my example the Init() function of the interface INetworkProvider would work fine but the ConnectToMaster() function won't work because the type SpecialParams is not recognized by my NetworkManager class what do i have to do ?

Create the SpecialParams Type in the 3rd party drive class and pass it to the ConnectToMaster Function ?

My Solution Example :

The INetworkProvider interface that all network providers will implement

public interface INetworkProvider {
    void Init();
    void ConnectToMasterServer(string ip,int port,SpecialParams sp);
}

The class that will drive from the 3rd party asset and implement INetworkProvider :

public FirstProvider : NetworkAsset.API,INetworkProvider {

    public void Init()
    {
      // Do init
    }

    public new void ConnectToMasterServer(strin ip,int port,SpecialParams sp)
    {
        // 3rd party API requires SpecialParams Type
        API.ConnectToMasterServer (ip,port,sp);
    }
}

My NetworkManager that will use the provider interface and call Init and ConnectToMaster fucn

public class NetworkManager : MonoBehaviour {

      // Define which network providers we have
    public enum ProviderType { FirstProvider,SecondProvider }

    public ProviderType providerType;

    private static INetworkProvider provider;

    // Unity awake function
    void Awake(){
        InitProvider ();
    }

    public void InitProvider()
    {
        switch (providerType) 
        {
            case ProviderType.FirstProvider:
                provider = gameObject.AddComponent<FirstProvider> ();
                break;

            case ProviderType.SecondProvider:
                provider = gameObject.AddComponent<SecondProvider> ();
                break;

            default:
                Debug.LogError ("Provider Script not found!");
                break;
        }

        provider.Init (); // would work fine
    }

    public void ConnectToMasterServer()
    {
        // error here because SpecialParams Type is not recognized here
        provider.ConnectToMasterServer ("127.0.0.1",6000,new SpecialParams); 
    }
}

Aucun commentaire:

Enregistrer un commentaire