Home > Software engineering >  c# 'static' variable not returning value
c# 'static' variable not returning value

Time:11-25

My problem I've run into

I've made a class with static variables that I wish to write and read data from, here is that data script:

LocalDataContainer.cs:

public class LocalRuntimeData 
    {
    /*
        Local Runtime Data is the container for all local data used during runtime.
    */

        public static LocalPlayer Player;
        public static AvatarInstance Avatar;
        public static LocomotionManager LocomotionManager;
        public static TrackedDevices TrackedDevices;

    /*
        Methods
    */
    }

But using another script to save data to the 'Player' variable from a 'Start()' method, and then load that data back into other components, nothing is returned- but what I don't understand is there are no errors coming from my IDE nor the Unity Editor.

Here is the second script that is trying to save data to the static 'Player' variable.

LocalPlayer.cs:

private void Start()
        {
            // Save player to LocalSpace runtime data.
            LocalRuntimeData.Player = transform.GetComponent<LocalPlayer>();

            ...

I also tried using LocalRuntimeData.Player = this; to just pass the component from it self without trying some useless workaround of just doing a loop around the transform back to the same component, but that didn't work.

The problem

Currently, I have no idea if that is even writing the data to the static variable, because when I try to use LocalPlayer Player = LocalRuntimeData.Player, nothing is actually returned to the component that has attempted to grab that static variable.

Yes, the component that is attempting to access that static variable is referencing the namespace that 'LocalRuntimeData.cs' us under. Reminder; there are no errors spat out from either my IDE or Unity Editor.

CodePudding user response:

if(transform.GetComponent<LocalPlayer>() == null)
  transform.AddComponent<LocalPlayer>();
LocalRuntimeData.Player = transform.GetComponent<LocalPlayer>();

CodePudding user response:

Solved

Rookie mistake on my part

There is a reason Unity provides both Awake() and Start() methods. Trying to do everything with the static variable in Start() is why scripts weren't able to get the variable, because it technically didn't exist when they tried to access the data at the same time it was written. Just had to change one script that was writing data to the variable to an Awake() method so the variable existed before the Start() method was called by the rest of the components.

  • Related