r/UnityHelp • • 1d ago

Static Class Isn't retaining Inspector references

I feel like I'm not understanding something about how static class instances work. every time i run this code it throws the null reference, but i had set the reference with the serialized field in the inspector. Is there something about the way static works or the way the awake function is called that is causing this issue? i feel like this sort of thing used to work.

Please Help

1 Upvotes

4 comments sorted by

1

u/FrancisJCat 1d ago

Things to check

  • Did you actually set the Cinemachine camera in the inspector?
  • Is CameraFollow on the scene?
  • Is the object CameraFollow attached to active and enabled on the scene?

If all of that checks, then check when SetTarget is called. Awake should run almost immediately after starting, but the order is not guaranteed. If another script is calling SetTarget from Awake, and that other script executed first, then instance will be null

1

u/UltraDuskknight 1d ago

The answer to the 3 questions is yes, (the second picture shows some of that) and the object calling the function is using a "LateAwake" function, but even if it was missing its bus i should just see it get set late right? since an inspector variable isn't worried about speed?. but it doesn't get set ever no matter how long i wait. unless awake runs before it checks inspector variables

1

u/FrancisJCat 1d ago

You can borrow my singleton. It's more reliable. See if it works with this

public abstract class SingletonBehaviour<T> : MonoBehaviour where T : SingletonBehaviour<T>
{
    public static T Instance => GetInstance();
    private static T _instance;
    
    private static T GetInstance()
    {
        // if initialized, return it
        if (_instance) return _instance;

        // if on scene, find it
        var found = FindObjectsByType<T>(FindObjectsInactive.Include);
        if (found.Length == 1)
        {
            _instance = found[0];
            return _instance;
        }

        if (found.Length > 1) throw new InvalidOperationException(
$"There are more than 1 singletons of type {typeof(T)} in the scene");

        return null;
    }
}

Then, to use it, make CameraFollow inherit from SingletonBehavior like so

public class CameraFollow : SingletonBehaviour<CameraFollow>
{
// remove "instance" and "Awake" since it's already provided by SingletonBehaviour
}

This is a bit more robust since it doesn't rely on Awake. As long as there is an instance on the scene, it should find it.

1

u/UltraDuskknight 1d ago

thank you for the help, that did actually lead me to the solution, my dumb ass forgot that i had put another camera follow script on the main camera when it had a different function hours ago. and your more robust function did tell me explicitly that there was more than one. i feel stupid, but thank you for your help.