I am trying to call a function in another c# script, that is attatched to another gameObject in my scene. I am creating an instance of the script LevelChanger
in the Grounded
one like this:
LevelChanger levelChanger;
Then, in the Awake()
function:
GameObject gameObject = new GameObject("LevelChanger");
levelChanger = gameObject.AddComponent<LevelChanger>();
then calling like this in an IEnumerator
:
levelChanger.FadeOut(true); // line 178
Then this is the LevelChanger
class:
using System.Collections;
using UnityEngine;
public class LevelChanger : MonoBehaviour
{
public Animator animator;
public void FadeOut(bool fadeIn)
{
animator.SetBool("Fade", true); // line 10
if (fadeIn) StartCoroutine(FadeInAsWell());
}
IEnumerator FadeInAsWell()
{
yield return new WaitForSeconds(0.9f);
animator.SetBool("Fade", false);
}
}
I've been trying to solve this problem for quite a while now, I checked everywhere (here, here, here, here and on other sites). I saw that because my LevelChanger
script is attatched to a gameobject, so it is MonoBehaviour
, it is not possible to create an instance of the class from another script, like this:
LevelChanger levelChanger = new LevelChanger();
or either "normally" like I was doing at first like this:
LevelChanger levelChanger;
Then just calling its functions like
levelChanger.FadeOut(true);
Most of the time I was getting a NullReferenceException
at runtime (at line 176), now directly in the LevelChanger
script (at line 10).
At this moment, I truly have no idea how to fix this: does anybody know how? (I'm still a beginner).
Thanks in advance!