can't access a public static int from another class. Value is always zero
In the class Spawner, I need to access the int L1score, which is declared as public static in the class HeroController. But when I access the value, as 'HeroController.L1score', the return value is always zero.
Here's the declaration in HeroController:
public class HeroController : MonoBehaviour {
public static int L1score = 0; //need this to report in Spawner
public void UpdateScore () {
GUIpoppedBubbles.text = "Popped: " +score;
L1score = score;
Debug.Log("HeroController; UpDateScore: "+L1score);
}
here's Spawner:
public class Spawner : MonoBehaviour {
int x = HeroController.L1score;
Debug.Log ("Spawner:EndGame. HeroController.L1score is " + x);
}
the output in the console: HeroController; UpDateScore: 77
Spawner. HeroController.L1score is 0
Could you post your entire spawner class? if the spawner is logging after the hero controller then there must be something else settings L1Score to 0. is there any other code that sets a value on this or is UpdateScore() the only place?
Answer by karadag · Feb 10, 2017 at 10:05 PM
Herocontroller.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HeroController : MonoBehaviour {
public static int L1score = 0; //need this to report in Spawner
void Update()
{
UpdateScore (20);
}
public void UpdateScore (int score)
{
L1score = score;
Debug.Log("HeroController; UpDateScore: "+L1score);
}
}
Spawner.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spawner : MonoBehaviour
{
int x;
void Update()
{
TestFunction ();
}
void TestFunction()
{
x = HeroController.L1score;
Debug.Log ("Spawner:EndGame. HeroController.L1score is " + x);
}
}
Answer by georgesmuga · Feb 11, 2017 at 06:15 PM
Thanks HenryStrattonFW -- my Spawner and HeroController run simultaneously. The Spawner puts out the targets and the HeroController shoots them down.
karadag has the right answer. Apparently, the UpDate method needs to know about the static variable, at least in my case. I simplified karadag's answer a little, and the variable shows up where I need it:
public class HeroController : MonoBehaviour {
public static int L1score = 0; //need this to report in Spawner
void Update()
{
L1score = score;
}
public void UpdateScore ()
{
GUIpoppedBubbles.text = "Popped: " +score;
Debug.Log("HeroController; UpDateScore: "+L1score);
}
If my answer correct please select my message for correct answer. Thanks