using UnityEngine;
using System.Collections;
public class test : MonoBehaviour {
public class AnotherClass
{
public int banana;
public void FruitMachine(int a, int b) {}
}
}
I can, within the same script, just write
AnotherClass fruit = new AnotherClass();
But what if I want to do this from another script in unity? The same code will fail, as the type AnotherClass is not known outside of the test.cs script.
Yes. You can create a new instance of ‘test’ by calling test myTest = new test();
To call a class inside a class you need to use the syntax I provided you with in my earlier post.
Also like @passerbycmc said, why are you looking to nest the class?
That’s a Unity-specific thing. Any MonoBehaviours need to have the same name as the file they’re in. But non-MonoBehaviour classes (like “AnotherClass”) can go wherever you want, even in the same files as a MonoBehaviour.
MonoBehaviours must match file names. Anything else can go anywhere. Often it becomes convenient to put data containers and helper classes at the bottom of the file they relate too.
One (very) last question: what happens if I have two classes in the file inheriting from MonoBehaviour? What name is the file supposed to have? Maybe it’s just not allowed to do that, right?
Yeah, that’s not allowed. The one that has a different name than the file will give you errors and you won’t be able to attach it by dragging the script file onto a game object. Each MonoBehaviour needs to be in its own file with the same name as the class. Anything that’s not a MonoBehaviour can be anywhere you like, including in the same files with a MonoBehaviour.