Reputation:
i am trying to make a level loading system for my game without switching scenes. i can load (intantiate) a level but i cant unload it (destroy it). here is the code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LevelLoadingSys : MonoBehaviour
{
public void loadLevelT()
{
GameObject LvlT = Instantiate(LevelTutorial);
load();
}
//unload levels
public void unloadLevelT()
{
Destroy(LvlT);
}
//levels
public GameObject LevelTutorial;
please help me if you have the time.
Upvotes: 0
Views: 1152
Reputation:
working code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LevelLoadingSys : MonoBehaviour
{
GameObject LvlT;
public void loadLevelT()
{
LvlT = Instantiate(LevelTutorial);
load();
}
public void unloadLevelT()
{
Destroy(LvlT);
}
//levels
public GameObject LevelTutorial;
}
Upvotes: 1
Reputation: 46
In this line: GameObject LvlT = Instantiate(LevelTutorial);
, the prefab you are instantiating is stored in a local variable (LvlT
).
This variable is droped at the end of its scope: the method loadLevelT()
but the instantiated gameobject still exists in the scene.
The variable should also not be available in the unloadLevelT()
method. Aren’t your editor and/or Unity displaying error about it ?
If you want this to work, you should declare LvlT
as a class field or property instead of a local variable so it could be accessible by all your class methods.
This could be a working version of your class:
public class LevelLoadingSys : MonoBehaviour
{
public void loadLevelT()
{
LvlT = Instantiate(LevelTutorial);
load();
}
//unload levels
public void unloadLevelT()
{
Destroy(LvlT);
}
//levels
public GameObject LevelTutorial;
private GameObject LvlT;
}
Note that I may have miss something. Try to post your whole class the next time so we do have the full context.
Upvotes: 1