Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
13 Jun 22 - 14 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
This post has been wikified, any user with enough reputation can edit it.
avatar image
2
Question by aCzyl · Jul 21, 2014 at 05:57 PM · variablefunctionstaticobject referencenon-static

ERROR - An object reference is required to access non-static member

 public class GameManager : MonoBehaviour {
 
     public int final_level_id;
 
     
     public static int current_score;
     public static int high_score;
 
     public static int current_level = 0;
     public static int unlucked_level;
 
     // Use this for initialization
     void Start () {
         /*
          * Built-in function.
          * This will make sure that this game object does not
          * get destroyed when a new scene is loaded.
          */
         DontDestroyOnLoad(gameObject);
     }
     
     // Update is called once per frame
     void Update () {
         print ("Level: " + (current_level+1) + "Final level: " + (final_level_id+1));
     }
 
     //You cannot call non-static variables/functions in a static variable/function.
     public static void level_completed()
     {
         //If the current level is less than the final level, load the next level.
         if(current_level < final_level_id)
         {
             //Increases the current level.
             current_level++;
 
             /*
              * Built-in class and function.
              * Loads the level(scene) with the specified id.
              * All levels(scenes) must be added to the build setting in Unity.
              * When a new level is loaded, all the code is refreshed(restarted).
              * We need to save the current_level variable, however.
              */
             Application.LoadLevel(current_level);
         }
         //Else, game over.
         else
         {
             print ("Congratulations, you win!");
         }
 
     }
 }






Inside this class, I make a public float called 'finallevelid', then try to use it inside the static function 'level_completed'. However, I get an error thrown saying:

Assets/Scripts/GameManager.cs(39,36): error CS0120: An object reference is required to access non-static member `GameManager.final_level_id'

I have tried making an object reference, but I think I am doing it wrong.

I would like to thank anyone for their help in advance.

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

3 Replies

· Add your reply
  • Sort: 
avatar image
10
Best Answer

Answer by ajkolenc · Jul 21, 2014 at 06:16 PM

In order to access variables that are not static from a static function, you need to have a reference to an instance of the class the variable belongs to. If your GameManager class is attached to an object in the scene, then this instance already exists, but currently you don't have a way to access it. The situation you are in calls for the use of the Singleton design pattern.

Basically, a Singleton is a class that will only ever have one instance during a scene; this instance is stored in a static variable so that it can be accessed by any other script. Singletons are useful for managers in Unity, because you can have non-static variables that are exposed in the Editor, yet can still be accessed by other scripts. Example:

 public class GameManager : MonoBehaviour {
 
     public static GameManager Instance;
     
     void Awake(){
         Instance = this;
     }
 }

When Awake is called on your instance of the GameManager script attached to an object in the scene, it will set itself to the static variable Instance so that any script can access the non-static variables it possesses. In your case, you can access the final_level_id variable by calling GameManager.Instance.final_level_id.

Comment
Add comment · Show 4 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image aCzyl · Jul 22, 2014 at 03:01 AM 0
Share

Thank you :)

avatar image Salazar · Apr 30, 2015 at 03:07 PM 0
Share

Works like a charm.

Thank you hard working community member, dedicated problem solver etc..

Regards,

avatar image xStinCtioN · Jul 29, 2015 at 10:53 PM 0
Share

Works! Thanks :)

avatar image VargaPD · Jun 11, 2016 at 12:56 PM 0
Share

And how do I do it without starting the game? I want an editor script, execute it from menu (or keypress, I don't care, if it's impossible with menu). But I want to get the name of a selected material's main texture. I think that is non-static, so I can't get it from static void. This is how far I got:

 using UnityEngine;
 using UnityEditor;
 using UnityEditor.VersionControl;
 using System.IO;
 using System.Collections;
 using System.Collections.Generic;
 
 [ExecuteInEdit$$anonymous$$ode()]
 public class $$anonymous$$aterialNames : Editor
 {
     
     public static $$anonymous$$aterialNames Instance;
     
     static string wgsDiffuseName;
     private Texture textureValue;
     
     
     [$$anonymous$$enuItem("WG/Diffuse name")]
     
     static void WGTextureName()
     {    
         wgsDiffuseName = $$anonymous$$aterialEditor.Get$$anonymous$$aterialProperty($$anonymous$$aterialNames.Instance.targets, "_$$anonymous$$ainTex").textureValue.name;
         Debug.Log(wgsDiffuseName);
     }
     
 }

I'm adding WG to stuff to be sure it never-ever used by anything else.

avatar image
0

Answer by robertbu · Jul 21, 2014 at 06:02 PM

To make this work, either 'finallevelid' needs to be static or you need to make 'level_completed' not be static. You cannot have a static function accessing non-static data in the class this way. A function that is not static can access both static and not static variables, but then other classes that want to use that function would need a reference to the component. They could not call it using the class name.

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image aCzyl · Jul 22, 2014 at 03:01 AM 0
Share

Thanks for the help :)

avatar image
0

Answer by Quarior · May 13, 2018 at 01:16 PM

Hello, I have also this problem. I test to edit a script I found and I have for this moment just this error but I don't know to fix. Here the code :

 using UnityEngine;  
 using System.Collections;  
 using System.Collections.Generic;  
 
 [RequireComponent (typeof (Rigidbody))]  
 public class GravityAttractorEdit : MonoBehaviour {
  
    public float gravity = -9.8f;
   
    public float Falloff = 2f;
   
    public static List<GravityAttractorEdit> GravityAttractors;
   
    Rigidbody rb;
   
    void Awake () {
        rb = GetComponent<Rigidbody> ();
   
        // Disable rigidbody gravity and rotation as this is simulated in GravityAttractor script
        rb.useGravity = false;
        rb.constraints = RigidbodyConstraints.FreezeRotation;
    }
   
    void FixedUpdate ()
    {
        foreach (GravityAttractorEdit gravityAttractor in GravityAttractors)
        {
            if (gravityAttractor != this) {
                GravityAttractorEdit.AttractEdit(gravityAttractor); //line where the error is it (Assets/Scripts/Spherical Gravity/GravityAttractorEdit.cs (32,26) : error CS0120: An object reference is required to acces non-static member)
            }
        }
    }
   
    void OnEnable ()
    {
        if (GravityAttractors == null)
            GravityAttractors = new List<GravityAttractorEdit>();
   
        GravityAttractors.Add(this);
    }
   
    void OnDisable ()
    {
        GravityAttractors.Remove(this);
    }
  
   
    public void AttractEdit(GravityAttractorEdit body) {
        Rigidbody rbToAttract = body.rb;
        Vector3 gravityUp = (rbToAttract.position - transform.position).normalized;
        Vector3 localUp = rbToAttract.transform.up;
        Vector3 direction = transform.position - rbToAttract.position;
         float distance = direction.magnitude;
   
        if (distance == 0f)
            return;
 
        Vector3 force = (gravityUp * gravity) / Mathf.Pow(distance, Falloff);
        // Apply downwards gravity to body
          rbToAttract.AddForce(force);
        // Allign bodies up axis with the centre of planet
          rbToAttract.rotation = Quaternion.FromToRotation(localUp,gravityUp) * rbToAttract.rotation;
    }
 }  

Thanks for help.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

5 People are following this question.

avatar image avatar image avatar image avatar image avatar image

Related Questions

C# script for calculating the distance between the player and objects 1 Answer

Static vs Non-static functions and variables 1 Answer

An object reference is required to access non-static member 0 Answers

Static variables not working inside Function Update() 1 Answer

variable = true from another script 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges