- Home /
Splitting with Partial Classes
Hello!
I am in the process of making an application that involves putting scripts onto GameObjects and I have entered a small roadblock. Could really do with some advice seeing I'm new to Unity and C#.
Being a student that has used C++, I am used to splitting up my content across multiple files and I would like to do the same within Unity.
The problem:
When searching online, the result I was directed towards was using partial classes to split my files, which if I'm not mistaken, requires you to have the same name class name in order to work - But what if my files are called different things?
public partial class MainStuff: MonoBehaviour //In a file called "Mainstuff"
{
public GameObject Handle; //This variable is required by initialise Object, and needs to stay in this class.
public void initialiseObject()
{
//Script stuff here. Calling the Handle GameObject.
}
}
public partial class Mainstuff: MonoBehaviour //In another file called "ObjectStuff"
{
//Where I would like to move initialiseObject()
}
I called both the classes MeshFunctions in order to prevent errors, but when I try apply the "ObjectStuff" file to the GameObject, It returns with: "Can't add script component 'ObjectStuff' because the script class cannot be found.
"But you need to rename Meshfunctions to the same name as ObjectStuff"
If I do so, then the class in ObjectStuff is unable to see the Gameobject Handle. Because I'm guessing that's how partial classes work. I'm usually used to things like headers that you can put your variables into.
Any pointers towards this would be brilliant thank you!
At least one of the files needs to match the class name and this file is the one you can attach to GameObjects. The whole class (the including the code in the other files) is serialized and shown in the Inspector (even if you cannot attach those other files to GO's) and you can see the partial classes all public fields there.
So, you cannot attach the "ObjectStuff" file to the GameObject, only the "Mainstuff", but should be enough
Of course you need to make sure the files are in the same namespace and assembly.
Your answer
