Why isn't the number subtracted in PlayerPrefs? - c#

Hello everyone In my code, when you click on the button, a number should be subtracted and saved in PlayerPrefs , the number is subtracted, but does not save . I also learned that the number is saved when you exit the game because of the OnApplicationQuit method, how to make the number normally saved?
public class Chest_Money : MonoBehaviour
{
public int NumCharector;
public int money;
public int Rand;
public Text text;
public GameObject NotMoney;
public GameObject[] Charectors;
public GameObject Panel;
public GameObject Panel2;
public bool bla2;
void Start()
{
money = PlayerPrefs.GetInt("Money_S", 0);
}
private void Awake()
{
}
#if UNITY_ANDROID && !UNITY_EDITOR
private void OnApplicationPause(bool pause){
if(pause){
//PlayerPrefs.SetInt("Money_S" , money);
}
}
#endif
private void OnApplicationQuit()
{
PlayerPrefs.SetInt("Money_S" , money);
}
void Update()
{
PlayerPrefs.SetInt("Money_S", money);
text.text = "$:" + money;
if(bla2 == true){
Panel2.SetActive(true);
}
}
public void Chest(){
if(money >= 100){
money -= 100;
PlayerPrefs.SetInt("Money_S", money);
StartCoroutine(Wait2());
}
else {
NotMoney.SetActive(true);
StartCoroutine(Wait4());
}
}
IEnumerator Wait4(){
yield return new WaitForSeconds(2);
NotMoney.SetActive(false);
}
IEnumerator Wait2()
{
yield return new WaitForSeconds(0);
SceneManager.LoadScene("Scins");
}
}

In general you can/should use PlayerPrefs.Save to force a save on certain checkpoints
By default Unity writes preferences to disk during OnApplicationQuit(). In cases when the game crashes or otherwise prematuraly exits, you might want to write the PlayerPrefs at sensible 'checkpoints' in your game. This function will write to disk potentially causing a small hiccup, therefore it is not recommended to call during actual gameplay.
I then also suggest you rather use a property like
private int _money;
public int money
{
get => _money;
set
{
_money = value;
PlayerPrefs.SetInt("Money_S");
PlayerPrefs.Save();
text.text = "$:" + money;
}
}
So it only updates the text and saves the value once it actually changes.
This way you don't need to update the text or set the value every frame in Update.

Related

Shuffling an array and assigning it to different buttons in Unity

I have an array that I am shuffling and then assigning to buttons. Depending on the item in the array, the button will perform a different function. This is currently my code, and it works, but is extremely inelegant.
I am currently shuffling the array first, then assigning the first 2 items of the shuffled array to the button text, and then using if statements to check whether or not the string matches so that it will execute a specific code for that string.
There is definitely a better way to do this, but I can't seem to figure it out.
public TextMeshProUGUI firstChoiceText;
public TextMeshProUGUI secondChoiceText;
public GameObject player;
public string[] upgrades =
{
"Speed Up",
"Fire Rate Up",
"Damage Up",
"Max Health Up"
};
public void Shuffle(string[] array)
{
for (int i = 0; i < array.Length; i++)
{
string tmp = array[i];
int rand = Random.Range(0, array.Length);
array[i] = array[rand];
array[rand] = tmp;
}
firstChoiceText.text = upgrades[0];
secondChoiceText.text = upgrades[1];
}
// Start is called before the first frame update
void Start()
{
Shuffle(upgrades);
}
public void FirstChoice()
{
Debug.Log("first choice clicked");
if (firstChoiceText.text == "Speed Up")
{
player.GetComponent<PlayerController>().playerSpeed += 1;
}
else if (firstChoiceText.text == "Fire Rate Up")
{
player.GetComponent<PlayerController>().fireRate -= 0.05f;
}
else if (firstChoiceText.text == "Damage Up")
{
player.GetComponent<PlayerController>().playerDamage *= 1.1f;
}
else if (firstChoiceText.text == "Max Health Up")
{
GameManager.maxHealth += 5;
player.GetComponent<PlayerController>().Heal(5);
}
Time.timeScale = 1;
gameObject.SetActive(false);
Shuffle(upgrades);
}
public void SecondChoice()
{
Debug.Log("second choice clicked");
if (secondChoiceText.text == "Speed Up")
{
player.GetComponent<PlayerController>().playerSpeed += 1;
}
else if (secondChoiceText.text == "Fire Rate Up")
{
player.GetComponent<PlayerController>().fireRate -= 0.05f;
}
else if (secondChoiceText.text == "Damage Up")
{
player.GetComponent<PlayerController>().playerDamage *= 1.1f;
}
else if (secondChoiceText.text == "Max Health Up")
{
GameManager.maxHealth += 5;
player.GetComponent<PlayerController>().Heal(5);
}
Time.timeScale = 1;
gameObject.SetActive(false);
Shuffle(upgrades);
}
One solution would be to create a Dictionary<string, Action<Player>> where your Action delegate corresponds to your string key and call the method via Action delegate based on the string key of the Dictionary, also moved your shuffle logic into it's own private method to reduce code duplication:
//Dictionary to hold string key/Action delegate pairs
private Dictionary<string, Action<Player>> _actions = new Dictionary<string, Action<string>>
{
{"Speed Up", (player) => player.GetComponent<PlayerController>().playerSpeed += 1;},
{"Fire Rate Up", (player) => player.GetComponent<PlayerController>().fireRate -= 0.05f;}
{"Damage Up", (player) => player.GetComponent<PlayerController>().playerDamage *= 1.1f;},
{"Max Health Up", (player) => { GameManager.maxHealth += 5;
player.GetComponent<PlayerController>().Heal(5); } }
};
//You could reduce your First And Second Choice down to using the
//dictionary to call the cooresponding Action delegate:
public void FirstChoice()
{
Debug.Log("first choice clicked");
_actions[firstChoiceText.text](player);
DoShuffle();
}
public void SecondChoice()
{
Debug.Log("second choice clicked");
_actions[secondChoiceText.text](player);
DoShuffle();
}
//Moved this into a method to reduce repetitive code
private void DoShuffle()
{
Time.timeScale = 1;
gameObject.SetActive(false);
Shuffle(upgrades);
}
You could create a base class for upgrades, and then use inheritance to split up all the logic that is now in the if statements to separate upgrade classes deriving from this base class. In the Unity world you might want to use ScriptableObjects for this.
public abstract class Upgrade : ScriptableOject
{
public abstract void Apply(PlayerController player);
}
[CreateAssetMenu(menuName = "Upgrades/Speed Up", fileName = "Speed Up")]
public sealed class SpeedUp : Upgrade
{
public override void Apply(PlayerController player)
{
player.playerSpeed += 1;
}
}
[CreateAssetMenu(menuName = "Upgrades/Fire Rate Up", fileName = "Fire Rate Up")]
public sealed class FireRateUp : Upgrade
{
public override void Apply(PlayerController player)
{
player.fireRate -= 0.05f;
}
}
Then you could create one scriptable object asset for each upgrade, and then assign all of them to your script into an Upgrade[] field.
[SerializeField] private TextMeshProUGUI firstChoiceText;
[SerializeField] private TextMeshProUGUI secondChoiceText;
[SerializeField] private PlayerController player;
[SerializeField] private Upgrade[] upgrades;
private Upgrade firstUpgrade;
private Upgrade secondUpgrade;
public void ApplyFirstUpgrade()
{
Debug.Log("first choice clicked");
ApplyUpgrade(firstUpgdade);
}
public void ApplySecondUpgrade()
{
Debug.Log("second choice clicked");
ApplyUpgrade(secondUpgrade);
}
private void Awake() => RandomizeUpgrades();
private void RandomizeUpgrades()
{
firstUpgrade = GetRandomUpgrade();
secondUpgdade = GetRandomUpgrade(firstChoice);
}
private Upgrade GetRandomUpgrade() => upgrades[Random.Range(0, upgrades.Length)];
private Upgrade GetRandomUpgrade(Upgrade ignore)
{
if(upgrades.Length < 2)
{
Debug.LogError("At least 2 upgrades need to be assigned before calling GetRandomUpgrade.", this);
return;
}
Upgrade resultCandiate = GetRandomUpgrade();
if(resultCandiate != ignore)
{
return result;
}
return GetRandomUpgdate(ignore);
}
private void ApplyUpgrade(Upgrade upgrade)
{
upgrade.Apply();
Time.timeScale = 1;
gameObject.SetActive(false);
RandomizeUpgrades();
}
The benefit with this sort of approach is that you can add more abilities easily without having to make any modifications to existing code, and without ending up with one giant class with hundreds of lines of code.

Passing data between scenes Errors

I have made a game manager making sure my data gets passed on from the first scene on to the next scene. Within the game manager, I have added certain scripts to ensure it gets passed. As you can see in the picture underneath.
The problem is that the score adds up at the first level, let's say I have 5 points. I go to level 2 and the UI shows my score as 0 (even tho I have nothing put as text within the score text) I kill 1 monster and the UI shows 6. So how can I put the UI to be showing it at all times? (Constant refresh?)
The second problem is that while the score manager does work. The health script cancels everything out when switching levels.
The user starts with 10 health. Takes damage in the first scene, but in the second scene, the user still has 10 health for some reason?
Game Manager
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameManager : MonoBehaviour {
public ActionButton PopupPrefab;
private ActionButton currentlySpawnedPopup;
public static GameManager instance = null;
void Awake () {
if (instance == null) {
instance = this;
} else if (instance != this) {
Destroy (gameObject);
}
Application.targetFrameRate = 60;
}
void Update () {
//if (Input.GetKeyDown(KeyCode.R)) {
// RestartScene ();
//}
}
public void InvokeRestartScene (float time) {
Invoke ("RestartScene", time);
}
public void RestartScene () {
SceneManager.LoadScene (0);
}
public void SpawnPopup (Vector2 position) {
DespawnPopup ();
currentlySpawnedPopup = Instantiate (PopupPrefab, position, Quaternion.identity) as ActionButton;
}
public void DespawnPopup () {
if (currentlySpawnedPopup != null) {
currentlySpawnedPopup.DestroySelf();
currentlySpawnedPopup = null;
}
}
public void FadePopup () {
if (currentlySpawnedPopup != null) {
currentlySpawnedPopup.FadeMe ();
currentlySpawnedPopup = null;
}
}
}
Score Manager
using UnityEngine;
using System;
using System.Collections;
public class ScoreManager : MonoBehaviour
{
public static ScoreManager Instance { get; private set; }
public int Score { get; private set; }
public int HighScore { get; private set; }
public bool HasNewHighScore { get; private set; }
public static event Action<int> ScoreUpdated = delegate {};
public static event Action<int> HighscoreUpdated = delegate {};
private const string HIGHSCORE = "HIGHSCORE";
// key name to store high score in PlayerPrefs
void Awake()
{
if (Instance)
{
DestroyImmediate(gameObject);
}
else
{
Instance = this;
DontDestroyOnLoad(gameObject);
}
}
void Start()
{
Reset();
}
public void Reset()
{
// Initialize score
Score = 0;
// Initialize highscore
HighScore = PlayerPrefs.GetInt(HIGHSCORE, 0);
HasNewHighScore = false;
}
public void AddScore(int amount)
{
Score += amount;
// Fire event
ScoreUpdated(Score);
if (Score > HighScore)
{
UpdateHighScore(Score);
HasNewHighScore = true;
}
else
{
HasNewHighScore = false;
}
}
public void UpdateHighScore(int newHighScore)
{
// Update highscore if player has made a new one
if (newHighScore > HighScore)
{
HighScore = newHighScore;
PlayerPrefs.SetInt(HIGHSCORE, HighScore);
HighscoreUpdated(HighScore);
}
}
}
Health Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class Health : MonoBehaviour {
public UnityEvent OnTakeDamageEvent;
public UnityEvent OnTakeHealEvent;
public UnityEvent OnDeathEvent;
[Header ("Max/Starting Health")]
public int maxHealth;
[Header ("Current Health")]
public int health;
[Header ("IsDeathOrNot")]
public bool dead = false;
[Header ("Invincible")]
public bool invincible = false;
public bool becomeInvincibleOnHit = false;
public float invincibleTimeOnHit = 1f;
private float invincibleTimer = 0f;
[Header ("Perform Dead Events after x time")]
public float DieEventsAfterTime = 1f;
void Start () {
health = maxHealth;
}
void Update () {
if (invincibleTimer > 0f) {
invincibleTimer -= Time.deltaTime;
if (invincibleTimer <= 0f) {
if (invincible)
invincible = false;
}
}
}
public bool TakeDamage (int amount) {
if (dead || invincible)
return false;
health = Mathf.Max (0, health - amount);
if (OnTakeDamageEvent != null)
OnTakeDamageEvent.Invoke();
if (health <= 0) {
Die ();
} else {
if (becomeInvincibleOnHit) {
invincible = true;
invincibleTimer = invincibleTimeOnHit;
}
}
return true;
}
public bool TakeHeal (int amount) {
if (dead || health == maxHealth)
return false;
health = Mathf.Min (maxHealth, health + amount);
if (OnTakeHealEvent != null)
OnTakeHealEvent.Invoke();
return true;
}
public void Die () {
dead = true;
if (CameraShaker.instance != null) {
CameraShaker.instance.InitShake(0.2f, 1f);
}
StartCoroutine (DeathEventsRoutine (DieEventsAfterTime));
}
IEnumerator DeathEventsRoutine (float time) {
yield return new WaitForSeconds (time);
if (OnDeathEvent != null)
OnDeathEvent.Invoke();
}
public void SetUIHealthBar () {
if (UIHeartsHealthBar.instance != null) {
UIHeartsHealthBar.instance.SetHearts (health);
}
}
}
I have thought of adding the following script on to my Health Script
But then I get the following error messages:
" Cannot implicitly convert type 'int' to 'bool'"
"The left-hand side of an assignment must be a variable, property or indexer"
void Awake()
{
if (health)
{
DestroyImmediate(gameObject);
}
else
{
(int)health = this;
DontDestroyOnLoad(gameObject);
}
}
The problem is that the score adds up at the first level, let's say I have 5 points. I go to level 2 and the UI shows my score as 0 (even tho I have nothing put as text within the score text) I kill 1 monster and the UI shows 6. So how can I put the UI to be showing it at all times? (Constant refresh?)
You can make one of the scripts set the UI text score when the scene is loaded.
void Start(){
// Loads the scoreText on start
scoreText.text = yourCurrentScore.ToString();
// Will work unless it has a "DontDestroyOnLoad" applied to it
}
The second problem is that while the score manager does work. The
health script cancels everything out when switching levels. The user
starts with 10 health. Takes damage in the first scene, but in the
second scene, the user still has 10 health for some reason?
In your health script, you had this:
void Start () {
health = maxHealth;
}
This resets your health everytime the scene loads and starts (Aka when you load to the next level). This causes the issue.
" Cannot implicitly convert type 'int' to 'bool'"
if (health)
The () for the if statement should be a condition (a question).
For example, doing health < 0 is valid since its saying "Is health less than 0?"
Doing health is not, since its just saying "10" (or some number).
"The left-hand side of an assignment must be a variable, property or
indexer"
(int)health = this;
If you wanted to change the value of health, just do health = 10 or health = some_Variable_That_Is_An_Integer

Unity: How to speed up score countdown

A quick question. I am playing with a small game from some tutorials but wanted to add a score that reduces each second. I managed to do so by the code provided below, but the score only lowers with 1 seconds at a time. I want to speed it up somehow, so it can drop each second by let's say 150. I tried a few things, but they didn't work and most of them didn't even record a change on the GUI inside the game. Any help is appreciated!
Code:
public class GameOver : MonoBehaviour {
public GameObject gameOverScreen;
public Text Score;
public Text Highscore;
bool gameOver;
private int score = 12000;
void Start () {
FindObjectOfType<PlayerController>().OnPlayerDeath += OnGameOver;
}
public void Update () {
Score.text = Mathf.Round(score - Time.timeSinceLevelLoad).ToString();
if (gameOver)
{
if (Input.GetKeyDown (KeyCode.Space))
{
SceneManager.LoadScene(1);
}
}
}
void OnGameOver()
{
gameOverScreen.SetActive (true);
Highscore.text = Mathf.Round(score - Time.timeSinceLevelLoad ).ToString();
gameOver = true;
}
}
Don't repeat yourself. Make a function to get the score.
int GetScore() {
return score - (int)Time.timeSinceLevelLoad * 150;
}
And then use it.
void Update() {
Score.text = GetScore().ToString();
}
Change this part
Score.text = Mathf.Round(score- Time.deltaTime*150).ToString();
--
public void Update () {
Score.text = Mathf.Round(score- Time.deltaTime*150).ToString();
if (gameOver)
{
if (Input.GetKeyDown (KeyCode.Space))
{
SceneManager.LoadScene(1);
}
}
}

How to generate random data without repeating in unity C#

Currently i'm developing a quiz kind of game for my gamification project. where i freeze the actual game when the player reaches some score and make question appear. If the answer is correct it will increase the speed of the player.And it will happen in a loop.
Here i'm using loadscene to load the index scene to avoid repeating of questions. The problem here is when the scene is loads it reloads the whole game instead of reloading the quiz part. Is there any way to do it ?
public class GameManager : MonoBehaviour
{
public Question[] facts;
private static List<Question> unansweredfacts;
private Question currentfacts;
[SerializeField]
private Text FactText;
[SerializeField]
private float TimeBetweenFacts = 3f;
[SerializeField]
private Text TrueAnswerText;
[SerializeField]
private Text FalseAnswerText;
[SerializeField]
private Animator animator;
[SerializeField]
public GameObject canvasquiz;
void Start()
{
if (unansweredfacts == null || unansweredfacts.Count == 0)
{
unansweredfacts = facts.ToList<Question>();
}
SetCurrentfact();
Debug.Log(currentfacts.Fact + "is" + currentfacts.IsTrue);
}
void SetCurrentfact()
{
int RandomFactIndex = Random.Range(0, unansweredfacts.Count);
currentfacts = unansweredfacts[RandomFactIndex];
FactText.text = currentfacts.Fact;
if (currentfacts.IsTrue)
{
TrueAnswerText.text = "CORRECT !";
FalseAnswerText.text = "WRONG !";
}
else
{
TrueAnswerText.text = "WRONG !";
FalseAnswerText.text = "CORRECT !";
}
}
IEnumerator TransitionToNextFact()
{
unansweredfacts.Remove(currentfacts);
yield return new WaitForSeconds(TimeBetweenFacts);
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
public void UserSelectTrue()
{
animator.SetTrigger("True");
if (currentfacts.IsTrue)
{
Debug.Log("CORRECT !");
}
else
{
Debug.Log("WRONG !");
}
StartCoroutine(TransitionToNextFact());
}
public void UserSelectFalse()
{
animator.SetTrigger("False");
if (!currentfacts.IsTrue)
{
Debug.Log("CORRECT !");
}
else
{
Debug.Log("WRONG !");
}
StartCoroutine(TransitionToNextFact());
}
Loading the scene again basically restarts it, what you want to do is change the TransitionToNextFact method in the following manner
IEnumerator TransitionToNextFact()
{
unansweredfacts.Remove(currentfacts); // remove the last shown question for the list
canvasquiz.SetActive(false); // disables the quiz canvas until the next question
yield return new WaitForSeconds(TimeBetweenFacts);
SetCurrentfact(); // sets the next random question from the list
canvasquiz.SetActive(true); // show the quiz canvas along with the new question
}
i would also combine the two methods UserSelectTrue and UserSelectFalse into one
public void UserSelected(bool isTrue)
{
animator.SetTrigger(isTrue ? "True" : "False");
if (currentfacts.IsTrue == isTrue)
{
Debug.Log("CORRECT !");
}
else
{
Debug.Log("WRONG !");
}
StartCoroutine(TransitionToNextFact());
}

Creation of a score system in unity

I am currently developing a simple 2D game to learn many things about game development.
Nevertheless, I have some issues to create a score system.
I want to update the score every second, and adding 1 point for each second, and stop the count when the game is over.
I start to write this
public class scoremanager : MonoBehaviour {
public int score;
public GUIText distance;
void Start () {
score = 0;
}
void Update () {
StartCoroutine(updateScoreManager(1f, 1));
distance.text = score.ToString();
}
IEnumerator updateScoreManager(float totalTime, int amount) {
score += amount;
yield return new WaitForSeconds (totalTime);
}
}
The issues are that nothing shows up in the GUIText so I don't know if it works. And how can I stop the count when the game is over?
First off, I think you should use uGUI since that's Unity's accepted solution for UI now: http://blogs.unity3d.com/2014/05/28/overview-of-the-new-ui-system/
I can't really say what the problem is with your GUIText since I don't know if the position is off or whatever but I can tell you how to manage the counting better.
You don't need to use the Update function, using the update function defeats the purpose of using a Coroutine to update your text. Using a Coroutine gives you some control over when it starts Updating and when it stops. So one solution is to get rid of the Update function entirely so you can control it better:
public class scoremanager : MonoBehaviour {
public int score;
public GUIText distance;
private Coroutine scoreCoroutine;
void Start () {
score = 0;
scoreCoroutine = StartCoroutine(updateScoreManager(1f, 1));
}
IEnumerator updateScoreManager(float totalTime, int amount) {
while(true) {
score += amount;
distance.text = score.ToString();
yield return new WaitForSeconds (totalTime);
}
}
// example of ending game
void EndGame() {
StopCoroutine(scoreCoroutine);
scoreCoroutine = null;
}
}
This might look weird (why am I using an infinite loop)? But that's the beauty of Coroutines, you can write code like this since the yield statement allows you to return from the code and come back to the same spot later. Normally a while loop would cause your game to crash, but a yield statement let's your create a time while loop!
Hope this helped!
I can see few glitches in your code. Let's cover it first.
You are calling Coroutine in Update with delay time of 1 second. This means your Coroutine is executing 30 or 60 times per second.
You are assigning text in Update too. This may be the reason that it refreshes the text (Not sure about this)
In your Coroutine your delay i.e. WaitForSeconds is of no use here, as nothing is happening after that line of code.
I'm modifying your exact code so that you can understand that what you want can be achieved by this too :)
public class scoremanager : MonoBehaviour {
public int score;
public GUIText distance;
public bool isGameOver = false;
void Start () {
score = 0;
StartCoroutine(updateScoreManager(1f, 1));
}
void Update () {
}
IEnumerator updateScoreManager(float totalTime, int amount) {
while(!isGameOver){
score += amount;
distance.text = score.ToString();
yield return new WaitForSeconds (totalTime);
}
}
}
What are the changes...
No code in Update.
Call Coroutine only once.
In Coroutine it is changing the score and distance both, once per totalTime second(s). Until the isGameOver flag is false. Just make it true when your game is over.
I guess simple solution to your problem is InvokeRepeating
//Invokes the method methodName in time seconds, then repeatedly every repeatRate seconds.
public void InvokeRepeating(string methodName, float time, float repeatRate);
So your transfomed code colud be
public class scoremanager : MonoBehaviour {
public int score;
public GUIText distance;
void Start () {
InvokeRepeating("updateScoreManager",1f,1f);
}
void Update () {
distance.text = score.ToString();
}
void updateScoreManager() {
score += 1;
}
The issues are that nothing shows up in the GUIText so I don't know if
it works
What happens? Is it always zero or nothing is displayed? If nothing - check coordinates, layer etc. to ensure you positioned it properly. Refere to http://docs.unity3d.com/Manual/class-GUIText.html
And how can I stop the count when the game is over?
Use StopCoroutine(updateScoreManager) on game over event and don't forget to set score to zero.
Actually saying your code design is not good. It would be great to implement State, Observer, Component patterns. With state you can implement game states like Game, GameOver. With Observer you can notify your scores component. With component you serve single responsibility principle by placing score logics to score component.
At least consider separate start game initialization, update component, and game over logics.
I'm going the skip the lecture on the pattern you are implementing because I don't know what the rest of your code looks like, but the source of your update problem is here:
IEnumerator updateScoreManager(float totalTime, int amount)
{
score += amount;
yield return new WaitForSeconds(totalTime);
}
In practice, when I run into these kinds of issues I separate the failing logic from the source application to help reduce the amount of noise.
So, when I prototype your algorithim (code below) what happens is that score is always zero because the StartCoroutine should be using the return value of updateScoreManager to do the updating when ever .Update() is called.
If my prototyping seems to match how you are trying to implement this code, then I can post how I would fix this later.
But basically, instead of returning IEnumerator return an int that updates the score and that might get you past this issue.
Unless you can describe the use-case where you need the IEnumerator somewhere else in the codes?
Execute Prototype:
class Program
{
static void Main(string[] args)
{
Ans34612672 Ans34612672 = new Ans34612672();
Ans34612672.Execute();
Console.ReadKey();
}
}
Prototype Wrapper Class:
public class Ans34612672
{
public Ans34612672()
{
}
public bool Execute()
{
bool retValue = false;
scoremanager Manager = new scoremanager();
Manager.Start();
while(Manager.score < 20)
{
Manager.Update();
}
Console.WriteLine(Manager.distance);
Console.ReadKey();
return retValue;
}
}
Prototype Classes:
public class scoremanager : MonoBehaviour
{
public int score;
public GUIText distance;
public void Start()
{
score = 0;
distance = new GUIText();
}
public void Update()
{
IEnumerator UpdateResults = updateScoreManager(1f, 1);
StartCoroutine(UpdateResults);
distance.text = score.ToString();
}
private void StartCoroutine(IEnumerator enumerator)
{
//Implement Logic
}
IEnumerator updateScoreManager(float totalTime, int amount)
{
score += amount;
yield return new WaitForSeconds(totalTime);
}
}
internal class WaitForSeconds
{
private float totalTime;
public WaitForSeconds(float totalTime)
{
this.totalTime = totalTime;
}
}
public class GUIText
{
internal string text;
}
public class MonoBehaviour
{
}

Categories