Question by
MarkoBorojevic · Jan 13, 2019 at 07:24 PM ·
c#unity 5
How do I start a Coroutine without having an instance of the script?
Hello! I'm trying to start a coroutine in a static void which is in a non-instantiated script. Once i try to call the void I get a NullReferenceException at line 12. Can anyone help me solve this issue?
Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using Game.Effects;
public class SceneLoader : MonoBehaviour
{
public static void LoadSceneByName(string sceneName, float fadeOutLength = 0f, float fadeInLength = 0f)
{
MonoBehaviour mono = new MonoBehaviour();
mono.StartCoroutine(LoadScene_Num(SceneManager.GetSceneByName(sceneName).buildIndex, fadeOutLength, fadeInLength));
}
static IEnumerator LoadScene_Num(int sceneIndex, float fadeOutLength, float fadeInLength)
{
Effects.DoFade(fadeOutLength, FadeType.FadeOut);
yield return new WaitForSeconds(fadeOutLength);
AsyncOperation operation = SceneManager.LoadSceneAsync(sceneIndex);
yield return operation.isDone;
Effects.DoFade(fadeInLength, FadeType.FadeIn);
}
}
Comment
Best Answer
Answer by Hellium · Jan 13, 2019 at 08:27 PM
Since SceneLoader
inherits from MonoBehaviour, take advantage of it
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using Game.Effects;
public class SceneLoader : MonoBehaviour
{
private SceneLoader instance;
public SceneLoader Instance
{
get
{
if( instance == null )
{
instance = new GameObject("SceneLoader").AddComponent<SceneLoader>();
}
return instance;
}
}
public static void LoadSceneByName(string sceneName, float fadeOutLength = 0f, float fadeInLength = 0f)
{
Instance.StartCoroutine(Instance.LoadScene_Num(SceneManager.GetSceneByName(sceneName).buildIndex, fadeOutLength, fadeInLength));
}
private IEnumerator LoadScene_Num(int sceneIndex, float fadeOutLength, float fadeInLength)
{
Effects.DoFade(fadeOutLength, FadeType.FadeOut);
yield return new WaitForSeconds(fadeOutLength);
AsyncOperation operation = SceneManager.LoadSceneAsync(sceneIndex);
yield return operation.isDone;
Effects.DoFade(fadeInLength, FadeType.FadeIn);
}
}
Your answer
Follow this Question
Related Questions
Black Scrreen after Splash Screen after deploy on HoloLens 1 Answer
Loot table problems 1 Answer
Game crashes on iPhone 11 0 Answers
Need help with Mute Button 1 Answer