About header files and creating libraries

Hey,
I’ve seen that in C you can use header files to include stuff from other files, like this:

file lib.h

int sum(int a, int b);

file lib.c

#include "lib.h"

int sum(int a, int b){
   return a+b;
}

file mainfile.c

#include lib.h

void main(){
int i =1;
int h=2;
int restult = sum(i,h);
//result should be 3
}

(And then you would compile the files and link the objects…)

How can i make something like this in c#, so that i can have a more compact main file, which would be the only one attached to my desired gameobject?

I don´t know C, but if you wanna include namespaces it is “using” in C#.

1 Like

C# just sort of… does it. You don’t need to “include” anything; any C# files built in the same assembly (which means, any C# files in your project folder, generally speaking) can all “see” each other.

If a particular thing is a set of functions (as opposed to “a thing”), you can make the class static.

If you want to put utilities in Utilities.cs:

public static class Utilities {
   public static int sum(int a, int b) {
      return a+b;
   }
}

And all your scripts can now access it:

void Update() {
Debug.Log("3 plus 5 is " + Utilities.sum(3, 5) );
}

It’s also recommended to put classes in specific namespaces for organizational purposes. This way, your “Utilities” class won’t collide with a “Utilities” class in a package you download from the asset store, for example. In which case:

namespace A_Box.CommonScripts {
public static class Utilities {
   public static int sum(int a, int b) {
      return a+B;
   }
}
}

In that scenario, to use classes in a different namespace than the one you’re currently in, you’d add “using A_Box.CommonScripts;” to the top of your C# file.

Does that help?

(edited: fixed using a wrong method name)

3 Likes

I’m using namespace and public static class
for example

Utilities.add(3, 5) <---- type error there its Utilities.sum(3, 5)

1 Like

That is exactly what i was looking for! Thanks for the help guys

A “using” line is the closest thing, but it is really just to let you write shorter lines of code. Everything can already see everything.

For example, this here:

using UnityEngine.UI;

public Text MyTextComponent;

Is effectively the same as this here:

public UnityEngine.UI.Text MyTextComponent;

So “using” statements are really optional in most cases. You can already get to anything else just by writing its full namespace each time.

2 Likes