Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

error CS0120: An object reference is required to access non-static member

Discussion in 'Scripting' started by pKallv, May 21, 2015.

  1. pKallv

    pKallv

    Joined:
    Mar 2, 2014
    Posts:
    1,129
    I do not understand why i get the errors? I have objects assigned to the properties.

    Code (CSharp):
    1. public class Replay_Script : MonoBehaviour {
    2.  
    3.     public GameObject gameBackground;
    4.     public GameObject go_pnl_Replay;
    5.     public Button btn_ExitReplay;
    6.     private bool firstRun;
    7.     private Color32 defaultBackgroundColor = Color.white;
    8.     private List<string> originalCardsPosition = new List<string>();
    9.  
    10.     public static void PrepareForReplay () {
    11.  
    12.         gameBackground.GetComponent<Renderer> ().material.color = Color.magenta;
    13.  
    14.         // DISPLAY THE REPLAY PANEL WITH BUTTONS
    15.         go_pnl_Replay.SetActive (false);
    16.  
    17.  
    18.         PositionObjectsOnInitialPositionsAndSortLevels ();
    19.  
    20.     }
    21.  
    22.     void PositionObjectsOnInitialPositionsAndSortLevels () {
    23.  
    24.     ...
    I get the following errors:
     
  2. ThomasCreate

    ThomasCreate

    Joined:
    Feb 23, 2015
    Posts:
    81
    I believe you'll find the answer here.
     
  3. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,744
    Your function is static - the function doesn't exist as a part of any particular object, but rather as a class function. Your gameBackground, etc member variables are local variables, and ARE attached to one instance of your object. When your static function goes looking for the instance variables, it has no way of knowing where to find them.

    Remove that 'static' from that function definition. I'm guessing that you have that there so that you can make the function call as Replay_Script.PrepareForReplay() from anywhere, and that removing 'static' will cause those references to be broken. If that's the case, I recommend turning the class into a singleton - have a single static variable, 'main' or 'instance' or what have you; in the script's Awake(), set main=this; and then you can call Replay_Script.main.PrepareForReplay().
     
  4. pKallv

    pKallv

    Joined:
    Mar 2, 2014
    Posts:
    1,129
    And you think i did not look there??? ...did but did not understand how that applied to my code.