- Home /
Accessing a variable from another script C#
Thanks in advance for reading my question and offering help.
I'm getting a bit frustrating as this has stalled my progress for far to long. I'm trying to access one variable from one script and modify it in another. Any time I try a solution I find here, it gives me an error of some sort. The least broken version I have will be posted here along with the error.
Here is the script with the float 'playerThirst' which is what I need to modify:
using UnityEngine;
using System.Collections;
public class PlayerNeeds : MonoBehaviour {
public static float playerThirst = 100;
public int playerExhaustion = 100;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
playerThirst -= Time.deltaTime / 30;
}
void OnGUI(){
GUI.Box (new Rect (0,0,100,30), "Thirst: " + playerThirst.ToString("F1") + "/100");
}
}
Here is the script that is broken. It has one purpose and that is to modify 'playerThirst':
using UnityEngine;
using System.Collections;
public class CactusInteract : MonoBehaviour {
public bool hasBeenDiscovered = false;
public float cactusWaterSupply = 100;
public bool collideWithCactus = false;
float thirsty = PlayerNeeds.playerThirst;
int thirstSubtract = 1;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(Input.GetKeyDown(KeyCode.E)){
cactusWaterSupply --;
thirsty += thirstSubtract;
}
}
error: Assets/CactusInteract.cs(9,37): error CS0236: A field initializer cannot reference the nonstatic field, method, or property `PlayerNeeds.playerThirst'
If someone could please, give me a detailed explanation on how to fix this I would be greatly thankful.
Thank you so much! You sir are a genius and I love you.
Answer by Vonni · Sep 05, 2013 at 12:20 AM
public PlayerNeeds playerNeedsReference; // Link in inspector
float thirsty = 0;
void Start () {
thirsty = playerNeedsReference.playerThirst;
}
// Or set playerThirst in playerNeedsReference to static and simply call it when you need it without having a duplicate varible for thirst, like so:
// .../
if(Input.GetKeyDown(KeyCode.E)){
cactusWaterSupply --;
PlayerNeeds.playerThirst += thirstSubtract;
}
// /...
Answer by Aarlangdi · Mar 26, 2014 at 04:49 AM
Guys,check this out, It has explained in very simple example about how to access variables from other classes --- http://aarlangdi.blogspot.com.au
But only one very specific way of doing it that requires global variables. http://unitygems.com/gotchas
Your answer
Follow this Question
Related Questions
Editing a variable from another script on collision 3 Answers
Using a script as a member variable in another script. 2 Answers
How to access gameObject variable script 2 Answers
C# How to access a variable in a script from an instance with the same script? 1 Answer
Change a Variable with another script not working (C#) 4 Answers