- Home /
C# Changing Float with External Script
hey guys i need help with this error. I'm using this accessor code as a test to see if i can access a float value in my hunger code as if i was eating food:
//this code is on the food btw
using UnityEngine;
using System.Collections;
public class Accessor : MonoBehaviour {
void Start()
{
GameObject Player = GameObject.Find("Player");
Hunger hunger = Player.GetComponent<Hunger>();
Hunger.hungerLevel += 1.0f;
}
}
this is my hunger script:
using UnityEngine;
using System.Collections;
public class Hunger : MonoBehaviour {
public float hungerLevel;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
hungerLevel -= Time.deltaTime;
}
}
when i try it it gives me this error:
Assets/Accessor.cs(9,16): error CS0120: An object reference is required to access non-static member Hunger.hungerLevel' and when i make the float static it gives me this error: ssets/PlayerHealth.cs(33,55): error CS0176: Static member
Hunger.hungerLevel' cannot be accessed with an instance reference, qualify it with a type name instead.
the piece of code its reffering to in my player Health script is this:
void Update () {
AddjustCurrentHealth(0);
if (thirst.thirstLevel <= 0 || hunger.hungerLevel <= 0)
{
curHealth = curHealth - 0.01f; // change the 10 to whatever damage you want
}
}
What do I do?
Answer by Sajidfarooq · Aug 23, 2013 at 07:52 AM
Change this line in the Accessor script:
Hunger.hungerLevel += 1.0f;
To this:
hunger.hungerLevel += 1.0f;
Basically, you are trying to access the class (Hunger), whereas you need to access the object you just created earlier (hunger).
That is a different problem for which you should post a separate question (with the rest of the code, i.e, AddjustCurrentHealth() etc)
$$anonymous$$y answer was for your question about error CS0120, which was caused by what I explained above.
To avoid this error in future, I would suggest using variable names that start with a lower case letter.
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Distribute terrain in zones 3 Answers
Float not working all the time? 1 Answer
for loop error 1 Answer
Multiple Cars not working 1 Answer