I’m new to Unity and have been coding in Swift for a while. Usually when creating game in Swift I would have a utility class that would exist outside of the game scene. I am trying to implement this in Unity C# and am having all sorts of trouble.
Here is my (simplified) Load script:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Load : MonoBehaviour {
public GameObject player;
public GameObject goal;
public Util util;
void Start () {
Instantiate(player, new Vector2(0, -4), Quaternion.identity);
Instantiate(goal, new Vector2(0, 4), Quaternion.identity);
if (util.level == 0) { // this is line 18
// do stuff
}
}
Here is my (simplified) Utility class:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Util {
public int level = 0;
}
I am getting a NullReferenceException: Object reference not set to an instance of an object
Load.Start () (at Assets/Scripts/Load.cs:18)
This is the first time I’m trying to access the utility class. I am thinking that I might need to attach it to a GameObject and call GetComponent each time I want to access it. But this seems very clumsy, is the a way to access the variables using dot syntax? Or is this approach contrary to the way Unity works?
Thanks,
James.