Encapsulation of server side code

Hey,
I will try to keep it short - tl;dr: I want to hide code in my client’s build, but keep it on the server.

Let say I have this methods:

[Server]
private void Hit(float amount)
{
    amount *= 1.1f; // This is secret and the client should never know/care about that
    health -= amount;
}

[Command]
public void Sword()
{
    Hit(10f);
}

If I understood it correctly, the client has a compiled version of the application(and it can be decompiled so the source code is unprotected) so my secret (1*1) is not hidden.

This is just an example, the real case involve things like secret http requests/keys/calculations and some business logic that the client should not know.

Best solutions I had, sorted from best case to worst

  • [Server] attribute can be exclude from the client’s build
  • Some sort of manual coding to let the compiler to exclude blocks of codes
  • Writing different projects/packages/builds for server and client

Any suggestions? What are the best practice? Did I missed something ?

bump

There’s built in support for this in Unity. In your build settings you can make defines, and use them to hide code from certain builds

#IF SERVER
// server code
#ENDIF

Just google unity build defines

Exactly what I wanted! Could be even more cool if that could be automatic for Server attributes :slight_smile:

1 Like

Could be tricky to do with attributes since those are compiler directives (They’re not a “Unity” thing, but something that dates back at least to C compilers, which is as far back as I go.) I think attribute are really runtime, so by using the compiler directives, you’re preventing the runtime from ever even seeing that code since it won’t be compiled. Doesn’t mean there isn’t a solution to do it that way, but it would probably require way more tooling than it’s worth. As other posts on the forum indicate, though, there’s not usually a need to hide your server code from the clients because they still have no way change the code on your server. If you want to prevent anyone but someone with a copy of the server binary from ever spinning up a server, however, eliminating the server code would be good!