Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Handling preliminary calculations/Object reference required error

Discussion in 'Scripting' started by halejoy7, Jun 28, 2020.

  1. halejoy7

    halejoy7

    Joined:
    Jun 24, 2020
    Posts:
    2
    Hello, beginner here;

    In my scripts I often have some settings inherited from the unity UI which are intuitive to the end appearance of the script, upon which I run some preliminary calculations to get more useful variables for ease of programming. I'm having a problem with the way this is implemented, so my question is both general and specific:

    Code (CSharp):
    1.     [System.Serializable]
    2.     public class Parameters
    3.     {
    4.         public GameObject someGameObject;
    5.         public float someFloat;
    6.         public float someOtherFloat;
    7.     }
    8.    
    9.     public Parameters parameters = new Parameters();
    10.    
    11.     public class Calculations
    12.     {
    13.         public float result1 = parameters.someFloat * parameters.someOtherFloat;
    14.         public float result2 = parameters.someFloat + (2 * parameters.someOtherFloat);  
    15.     }
    16.  
    17.     public Calculations calculations = new Calculations();
    This code returns 'An object reference is required for the non static field, method, or property 'updater.parameters'. Clearly C# is not happy with how I'm passing my parameters into my preliminary calculations...

    Specific question: how do I make the error go away?

    General question: how best to handle this sort of preliminary calculation, where the result of the calculation is something I want to call throughout my script? (This code is a reduced example of more complex systems, that has the essential mistakes in it.)

    Any help is much appreciated!
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,893
    It would help if you posted your entire verbatim script, and the entire error message. The error message has numbers in it which tell you the line number where the error is.

    One issue I see is that the Calculation class is trying to use a field from the class it's contained in (assuming all of this code is inside another class, which is unclear).