简体   繁体   中英

Public static member appears to be null inside public static method

I am writing a method that lives outside of main and interacts with a public static member. I initialized the member inside main() and proceed to try and use it inside my method, and the pointer is null:

public class Program
{   
    …
    public static EulerPID PitchAxis;

    public static EulerPID RollAxis;
    …   
     public static void FixedUpdateRoutine(object state)
     {  
        …   
        if (…)
        {   
            if (…)
            {   
               …    
                ///Apparently PitchAxis and RollAxis are NULL?
                double[] output = new double[] { PitchAxis.UpdatePID(FloatQs[1]),          RollAxis.UpdatePID(FloatQs[2]) };
                …
             }
          }
        }
    public static void Main() 
    {
      …
      // initialize PID controllers
      EulerPID PitchAxis = new EulerPID(0.0001, 0.001, 0.001);
      EulerPID RollAxis = new EulerPID(0.0001, 0.001, 0.001);
      …
}

help? Thanks in advance!

What your main function is doing is creating local copies of EulerPID . What your main should look like is:

public static void Main() 
{
  …
  // initialize PID controllers
  PitchAxis = new EulerPID(0.0001, 0.001, 0.001);
  RollAxis = new EulerPID(0.0001, 0.001, 0.001);
  …
}

You are declaring two local variables with the same name of the global ones.
The result is that the two globals are hidden by the locals and are never initialized.
And when you try to use them in the FixedUpdateRoutine you get the Null Reference Exception

To initialize the global variables you need to remove the type before the name.

PitchAxis = new EulerPID(0.0001, 0.001, 0.001);
RollAxis = new EulerPID(0.0001, 0.001, 0.001);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM