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
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);
}
}
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