0

I have 2 classes.

public class GameManager : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        var a = new Routine();
        a.StartRoutine();
    }
}
public class Routine : MonoBehaviour
{
    public void StartRoutine()
    {
        StartCoroutine(test());
    }
    IEnumerator test(){
        Debug.Log("MSG");
        yield return null;
    }
}

I put GameManager on Camera, run game and get NullReferenceException

NullReferenceException
UnityEngine.MonoBehaviour.StartCoroutine (System.Collections.IEnumerator routine) (at <d815b7efac424eeb8e053965cccb1f98>:0)
Routine..ctor () (at Assets/Routine.cs:9)
GameManager.Start () (at Assets/GameManager.cs:10)

So what is wrong with this code?

Roman
  • 47
  • 7
  • I have changed the code a little bit, but still it throws exception – Roman Apr 01 '20 at 11:57
  • @UnholySheep there is no constructor involved here at all ... – derHugo Apr 01 '20 at 12:03
  • Class Routine and Game manger are in same script? or 2 scripts different and routine is not linked to any Gameobject? – Frenchy Apr 01 '20 at 12:04
  • 4
    `new` is absolutely **forbidden** for classes of type `MonoBehaviour` and you should see a warning regarding this in the console. The only way to instantiate them is to either spawn a prefab with them attached via `Instantiate` or use `someGameObject.AddComponent()` see e.g. [Why in unity i'm getting the warning: You are trying to create a MonoBehaviour using the 'new' keyword?](https://stackoverflow.com/questions/40640553/why-in-unity-im-getting-the-warning-you-are-trying-to-create-a-monobehaviour-u) – derHugo Apr 01 '20 at 12:08

1 Answers1

1

You're attempting to create a new Monobehaviour object with this line: var a = new Routine();. Instead, you could:

Create a gameobject and add the Routine.cs script as a component.

Then back in your GameManager.cs

public class GameManager : MonoBehaviour {
    public GameObject go;

    void Start() {
        Routine routine = go.GetComponent<Routine>();
        routine.StartRoutine();
    }
}

Then back in the Unity Editor, add the gameobject containing the Routine.cs script to the GameManager.cs empty go field

ctsalidis
  • 11
  • 3