- Home /
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.
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
.
Works like a charm.
Thank you hard working community member, dedicated problem solver etc..
Regards,
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.
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.
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.
Your answer
Follow this Question
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