How could you modify the code below to use a static keyword? C# using UnityEngin
ID: 3712200 • Letter: H
Question
How could you modify the code below to use a static keyword?
C#
using UnityEngine.UI;
using UnityEngine;
public class ScoreManager : MonoBehaviour
{
private GameController gameController;
public Text scoreText;
private int score;
void Start()
{
GameObject gameControllerObject = GameObject.FindWithTag("GameController");
if (gameControllerObject != null)
{
gameController = gameControllerObject.GetComponent<GameController>();
}
if (gameController == null)
{
Debug.Log("Cannot find 'GameController' script");
}
score = 0;
UpdateScore();
}
public void AddScore(int newScoreValue)
{
score += newScoreValue;
UpdateScore();
}
void UpdateScore()
{
scoreText.text = "Score: " + score;
}
}
Explanation / Answer
Some rules for static in c#:
- Only one copy of static fields exists
- Static methods can access only static fields
- Class can have both static and non-static members
- A static member does not belong to the object rather it belongs to class
- Static constructor can't be parameterized
- Static methods are shared methods
- A static class contains only static members
- A static class cannot be instantiated
using UnityEngine.UI;
using UnityEngine;
public static class ScoreManager : MonoBehaviour
{
private static GameController gameController;
public static Text scoreText;
private static int score;
public static void Start()
{
static GameObject gameControllerObject = GameObject.FindWithTag("GameController");
if (gameControllerObject != null)
{
gameController = gameControllerObject.GetComponent<GameController>();
}
if (gameController == null)
{
Debug.Log("Cannot find 'GameController' script");
}
score = 0;
UpdateScore();
}
public static void AddScore(int newScoreValue)
{
score += newScoreValue;
UpdateScore();
}
void static UpdateScore()
{
scoreText.text = "Score: " + score;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.