C# preprocessor directives or how to split your code (free project)

I’m pretty sure you do not want to include Server code to the Client build, for instance – your server code contains important SQL passwords or any sort of account infromation, instead of lead two different projects you could simply mark your code #if Server and #if Client.

Let’s take UNET NetworkManager as example

NetworkManagerCustom.cs

using UnityEngine;
using System.Collections;
using UnityEngine.Networking;

public class NetworkManagerCustom : NetworkManager
{
    string login;
    string password;

    void Awake()
    {
        NetworkManager.singleton = this;
    }

    public override void OnServerDisconnect(NetworkConnection conn)
    {
        GameObject player = conn.playerControllers[0].gameObject;
        Save(player);
    }

    //server save system
    void Save(GameObject player)
    {
        login = "DatabaseLogin";
        password = "DatabasePassword";
        
        //save...
    }
}

After decompile client will see code from the NetworkManagerCustom so there is login and password:

screenshot_3

We can avoid it with adding Defines. I will attach the GlobalDefinesWizard script with test project, you should put the script in the Editor folder. Also there is a quick vid about how to use it, thanks prime[31].

After adding your defines, you can use it. Here is basic Server and Client defines.

Untitled-3

So in order to not include the Server code you should put Server define.

Here is modified code of NetworkManagerCustom.cs

using UnityEngine;
using System.Collections;
using UnityEngine.Networking;

public class NetworkManagerCustom : NetworkManager
{
    string login;
    string password;

    void Awake()
    {
        NetworkManager.singleton = this;
    }

    public override void OnServerDisconnect(NetworkConnection conn)
    {
        GameObject player = conn.playerControllers[0].gameObject;
        Save(player);
    }

#if Server

    //server save system
    void Save(GameObject player)
    {
        login = "DatabaseLogin";
        password = "DatabasePassword";
        
        //save...
    }

#endif

}

The code between #if Server, and #endif won’t be included in the client build.

So here is how it looks after we adding our defines and made a build:

screenshot_5

As you can see, the script NetworkManagerCustom, doesn’t contains important Server code on Client Side. But this code will work on Server Side.

Download:

GlobalDefinesWizard.cs

Source project

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s