Hi, I have written a line of code that controls wether a flare gun appears or not, but i referenced a variable on another piece of code on a game manager game object and it bugs out, i even tried to make it a static variable and didn’t work. Code attached below, thanks.
private ItemManager items;
// Update is called once per frame
void Start()
{
items = GameObject.Find("GameManager").GetComponent<ItemManager>();
}
void Update ()
{
if (items.HasFlareGun == true)
{
activateFlare();
}
else
{
gameObject.SetActive(false);
}
I really want to smack the people making the tutorials showing Find. It’s an absolutely awful way to access an object as it’s extremely prone to null reference errors if anything is the slightest bit off, and depending on scene complexity can be anywhere from a few times slower to hundreds of times slower. It can take seconds per call.
If you have a single instance of an object in a scene that you need to access the simplest approach is to have the object provide the reference for you and then whenever you need to access the object you simply query the static field holding the instance reference.
Modify your class to add the following code:
public class ItemManager : MonoBehaviour
{
private static ItemManager _Instance; // reference field (static makes it so only one copy of the field exists for all instances)
public static ItemManager Instance => _Instance; // makes it read-only to avoid modifying by accident
private void Awake()
{
if (_Instance != null) // if the first one was already found delete any accidental second copies
{
DestroyImmediate(gameObject);
}
else // finds the first instance, assigns the reference field, and makes it persist through scenes
{
_Instance = this;
DontDestroyOnLoad(gameObject); // remove if you don't want it to persist between scene loads
}
}
}
Haha, that’s fair. I don’t use the manual approach myself but we weren’t told anything about their manager and I was worried about overwhelming them in the event that they’re setting data in the manager and would need the prefab variant. I don’t actually know how complex it is from a beginner’s perspective.