In UnityScript, if I had a class named Zone in the script named Uni, and I wanted to create an instance in other script, I could just say
var oneZone : Zone.
In C# I have to use the name of the script eg
private Uni.Zone oneZone.
I don’t understand why this is and I’m worried that I am screwing something up because I don’t see this mentioned anywhere in any Google search.
If you don’t define your Class inside your MonoBehaviour - just put it outside - then you can just create it like the US version.
US is basically fiddling to generate a class for your script behind the scenes, and then it’s guessing you didn’t want to embed the extra class when you write one in the file. (You can make it embed it by explicitly defining your behaviour class as well if you really want to).
So just have multiple classes, don’t embed one inside the other if you don’t want to reference it that way.
It depends of the scope where the class is declared. You have the namespace then the class (might need confirmation on that).
Example 1 : The class is a tool used internally by main class and nobody else need it.
public class MainClass
{
private Tool tool; // A higher accessibility would raise an error here
public void DoStuff(){ /* stuff where tool is used */ }
// This class won't be used by anyone else, we can make it private.
// It could be protected if you wish to inherit from MainClass.
private class Tool{ /* stuffs */ }
}
Example 2 : The Tool class is needed to use the MainClass, but only in that case. It is its only purpose, so you can declare it inside the main class.
public class MainClass
{
// Notice that the public function take a Tool in parameter.
// This mean whoever call it needs access to Tool
public void DoStuff(Tool tool){ /* stuff where tool is used */ }
// That's why you make it public.
// To instantiate a tool object, you'll call "new MainClass.Tool()"
public class Tool{ /* stuffs */ }
}
Example 3 : The tool class can be used in a lot of situations, not only with the main class. You can then declare it outside. Think Vector3, for instance.
// By declaring it outside of MainClass, you can
// use at a usual class (Tool t = new Tool();)
public class Tool{ /* stuffs */ }
public class MainClass
{
public void DoStuff(Tool tool){ /* stuff where tool is used */ }
}
PS : If I made any mistake, which is fairly possible, feel free to edit me.