noob question: organizing code?

hello all!

I recently started working with Unity, I got the trial version a little over a month ago and bought the indie version a few days ago :smile:

To be honest I am not a very good programmer (in fact I used to be a 3d artist, then turned level designer and I’m currently working as a game designer). However I do have quite a lot of scripting experience and some programming experience.

I’m currently working on a sort of ā€œsporting gameā€ in unity. Some of my code is starting to get out of hand and I want to spread the code over several files. Can this be done in unity?

I noticed 1 script file turns up as a ā€œcomponentā€ in the editor. Would it be possible to write a class in a separate script file and then use the methods from that class in other scripts? (I’m using c#)

For example I have this class that controls player movement and it uses some functions I wrote to do some geometry stuff (rotating etc). The same functions are used in another script that control a different game object but for now I simply copy/pasted the functions into the other script.

It would be much nicer if I could just put the geometry functions in a separate file and then use them in my other scripts…

can this be done?

thanks in advance!

Well, in JS you can define classes, then instantiate them and use those objects like in any program, so I imagine you can do the same with C#. I do it all the time in JS. No need to add them as components (althought sometimes using the component method is advantageous).

You’re supposed to it that way; Unity is heavily designed around it. :slight_smile:

–Eric

but do I have to add each script as a component? Or can I simply use code from other scripts without adding them as components?

Depends…static functions can be just scripts somewhere in your project and don’t need to be components. Otherwise they do have to be attached to some object, but can be accessed from other scripts. It’s typical to make a ā€œgame managerā€ object, which may have generic functions that can be used by other objects.

–Eric

great! Thanks for the help.

I’ve created a VectorFunctionsClass that has a couple of methods I use frequently, I then access those by creating an instance of that class like so:

protected VectorFunctionsClass VectorFunctions = new VectorFunctionsClass();

which works like a charm.
Is this the proper way to do it?

That will certainly work, but you can skip creating a new object by making the VectorFunctionsClass class and its functions static. Then whenever you need to access a particular function you can use VectorFunctionsClass.YourFunctionName();