Static function not working in between screen
I'm coding my RPG battle system so for that I created a scriptable object called enemy.
I created a function battle to load my battle scene along with the enemy object:
public static void Battle(Enemy enemy){
SceneManager.LoadScene(1);
GameObject.FindWithTag("Enemy").GetComponent<EnemyObject>().enemy = enemy;
}
NOTE: I already made GameManager Don't destroy on load so that it remains on the scene. Now the scene is loading all right but I encountered a null reference exception.
I called Battle(toxopus);
after a conservation of the character. My project is 2D but that's not a problem. The error says that there's no enemy object so I believe it does the finding before switching scenes. Any suggestions?
Answer by Frisk17 · Mar 02, 2019 at 07:43 AM
I FIXED that! I created 2 static variables static bool searching; static Enemy currentEnemy;
public static void Battle(Enemy enemy)
{
if (enemy == null) { Debug.Log("Stop Battle!! Enemy is Null"); return; }
SceneManager.LoadScene(1);
currentEnemy = enemy;
searching = true;
}
Along with this I added some code to update. The answer by @sath was correct but due to some reason it didn't worked without update.
private void Update()
{
if (Input.GetKeyDown(KeyCode.F4)) ChangeResolution();
if(searching)
{
do
{
Debug.Log("LOADING");
} while (SceneManager.GetActiveScene().buildIndex != 1);
GameObject.FindGameObjectWithTag("Enemy").GetComponent<EnemyObject>().enemy = currentEnemy;
searching = false;
}
}
Thanks to everyone who tried helping.
Answer by sath · Mar 01, 2019 at 02:33 PM
@Gamingdude1 Hi, try this (not tested)
public static void Battle(Enemy enemy)
{
if (!enemy) { Debug.Log("Stop Battle!! Enemy is Null"); return; }
SceneManager.LoadScene(1);
FindEnemy(enemy);
}
static void FindEnemy(Enemy enemyCurrent)
{
GameObject enemyTarget = null;
while (enemyTarget == null)
{
enemyTarget = GameObject.FindWithTag("Enemy");
//just in case
if (enemyTarget) break;
}
EnemyObject enemyObject = enemyTarget.GetComponent<EnemyObject>();
if (!enemyObject) { Debug.Log("EnemyObject not found!!"); return; }
enemyObject.enemy = enemyCurrent;
Debug.Log("Found Enemy!!");
}
Well this SHOULD work but due to some reason my $$anonymous$$ac shows loading sign and application not responding. As I can't see any Debug logs I believe it's stuck in the scene load due to some reason or maybe be scene is loaded and not showing and it's stuck in the while loop.
I tried commenting areas... it is because of the while loop... though I couldn't find the cause..
Putting the while loop with just a debug log even crashes..