using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class LevelGeneration : MonoBehaviour {
//variables here
public void CreateWorld() {
//code for generating level
}
}
And GameManager.cs:
public class GameManager : MonoBehaviour {
void Start() {
}
}
Two questions:
I want to call CreateWorld() from GameManager, but when I tried to do smth like LevelGeneration lvlGen; and in start() lvlGen.CreateWorld() it didn’t work - nothing happened. Only an error about instance of an object…
The main thing I’m trying to achieve here is the code organization. So, When I do thing i described above - do I have to repeat all the variables from LevelGeneration in the GameManager…?
And ideally I’d like to put only GameManager.cs onthe gameobject, and leave all other scripts laying in the folder - am I on the right track?
Yes, you can have only GameManager to be on a gameobject. Just remove the MonoBehaviour inheritance from the LevelGeneration class definition. It is, of course, depends on what functionality you want to have there, as by doing this you will lose access to what MonoBehaviour provides (such as ability to start coroutines, etc.).
If you go this route, you can then do the following in your GameManager object:
public class GameManager : MonoBehaviour {
void Start() {
LevelGeneration levelGeneration = new LevelGeneration();
levelGeneration.CreateWorld();
}
}
It’s very likely LevelGeneration class will need some information from the GameManager about what exactly to create, where to put it in the scene, etc. If you can provide more details/specifics on how you want this to behave, I may be able to suggest other ways to organize the code.
There are two methods to do this:
First method is the Unity way, the proper one to use in most situations.
In your GameManager script you instantiate an instance of LevelGeneration MonoBehaviour. You have to attach both scripts on the same gameObjects tho (or you can put it on another gameObject then read that gameObject into the variable and then do the same). This is done like this:
public class GameManager : MonoBehaviour {
private LevelGeneration levelGen;
void Start() {
levelGen = getComponent<LevelGeneration>();
levelGen.CreateWorld();
}
}
Second method is to make CreateWorld method as a static public method. This fits your need more, tho you have to make every method and the script static too. This is a little less memory efficient especially when you’re working with a lot of variables.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public static class LevelGeneration {
//variables here
public static void CreateWorld() {
//code for generating level
}
}
then you can call it from GameManager as
LevelGeneration.CreateWorld();
public class GameManager : MonoBehaviour {
void Start() {
LevelGeneration.CreateWorld();
}
}