I have two scenes. In one scene there are villages that have Level script attached. This script contains information about the level and most importantly prefabs of monsters that should be spawned for this level.
When a village is clicked it loads a second scene in which it should spawn monsters that were assigned to the village in the Level script. I don’t know what is the best way to pass these prefabs from the village to the next scene to, where spawner will use them. What I did is:
I have a static variable, which is a reference to the Level script from the selected village.
public class ApplicationModel
{
public static Level selectedLevel = null;
}
When village is clicked it assigns the Level script to the static variable.
public class Level : MonoBehaviour
{
public GameObject[] easy;
public GameObject[] medium;
public GameObject[] hard;
public GameObject boss;
public int totalUnits;
public float spawnTime;
void OnMouseDown()
{
ApplicationModel.selectedLevel = this;
Application.LoadLevel("forest");
}
}
When a forest scene is loaded, in a different script I retrieve information and prefabs from the static selectedLevel
variable
public class LevelSceneManager : MonoBehaviour
{
public EnemySpawner spawner;
void Start ()
{
if(spawner != null && ApplicationModel.selectedLevel != null)
{
spawner.easy = ApplicationModel.selectedLevel.easy;
spawner.medium = ApplicationModel.selectedLevel.easy;
spawner.hard = ApplicationModel.selectedLevel.hard;
spawner.boss = ApplicationModel.selectedLevel.boss;
spawner.spawnTime = ApplicationModel.selectedLevel.spawnTime;
spawner.totalUnits = ApplicationModel.selectedLevel.totalUnits;
}
}
}
The problem is that ApplicationModel.selectedLevel
is null, which might be because the GameObject of that script was destroyed, but still I can access its variables e.g. ApplicationModel.selectedLevel.easy
is not null. While this approach works fine if I will remove if(ApplicationModel.selectedLevel != null)
statement, I’m concerned about memory leaks that it might cause. When you will go back to the world scene, all arrays from the previously selectedLevel
e.g. easy are still alive. What if you click a different village, will it destroy these arrays from the previous selectedLevel
or will they be kept somewhere in the memory? Is there any better solution to pass prefabs assigned to a script in the editor from one scene and access them in the other scene?