Unity Number Wizard Back Button - c#

I just created a Number Game witch guesses what number you are thinking of and shows it to the screen as a TextMeshProUGUI element. I want to add a back button so that when you press the incorrect button the TextMeshProUGUI element displays the value that was displayed before the user pressed the incorrect button.
Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.UI;
public class NumberWizard : MonoBehaviour {
[SerializeField] SceneLoader sceneLoader;
[SerializeField] int max;
[SerializeField] int min;
[SerializeField] TextMeshProUGUI guessText;
int guess;
// Use this for initialization
void Start ()
{
StartGame();
}
void StartGame()
{
NextGuess();
}
public void OnPressHigher()
{
min = guess + 1;
NextGuess();
}
public void OnPressLower()
{
max = guess - 1;
NextGuess();
}
void NextGuess()
{
guess = Random.Range(min, max+1);
guessText.text = guess.ToString();
}
public void Back()
{
//Back code should go here
}
}
Scene View

you just have to remember the last guess:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.UI;
public class NumberWizard : MonoBehaviour {
[SerializeField] SceneLoader sceneLoader;
[SerializeField] int max;
[SerializeField] int min;
[SerializeField] TextMeshProUGUI guessText;
int guess;
int lastGuess;
int lastMin;
int lastMax;
// Use this for initialization
void Start ()
{
StartGame();
}
void StartGame()
{
NextGuess();
}
public void OnPressHigher()
{
lastMin = min;
min = guess + 1;
NextGuess();
}
public void OnPressLower()
{
lastMax = max;
max = guess - 1;
NextGuess();
}
void NextGuess()
{
lastGuess = guess;
guess = Random.Range(min, max+1);
guessText.text = guess.ToString();
}
public void Back()
{
guess = lastGuess;
min = lastMin;
max = lastMax;
guessText.text = guess.ToString();
}
}
if this is not what you want, please write a comment and i will edit the answer

Related

Can someone tell me how to make a cooldown for the bullet?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletParticle : MonoBehaviour
{
public float damage = 10f;
public ParticleSystem particleSystem;
public GameObject spark;
List<ParticleCollisionEvent> colEvents = new List<ParticleCollisionEvent>();
private void Update()
{
if (Input.GetKeyDown(KeyCode.Mouse0))
{
particleSystem.Play();
}
}
private void OnParticleCollision(GameObject other)
{
int events = particleSystem.GetCollisionEvents(other, colEvents);
for (int i = 0; i < events; i++)
{
Instantiate(spark, colEvents[i].intersection, Quaternion.LookRotation(colEvents[i].normal));
}
if (other.TryGetComponent(out enemy en))
{
en.TakeDamage(damage);
}
}
}
Does anyone know how to make the bullet have a cooldown please tell me?
A guy said to do something with the input so when the bullet shoots it has a cooldown.
`
that's a simple method using a timer it should be something like
using UnityEngine;
using System.Collections;
public class SimpleTimer: MonoBehaviour {
// i assigned the timer at 3 seconds
public float cooldownBullet = 3.0f;
public bool canShoot=false;
Update(){
targetTime -= Time.deltaTime;
if (Input.GetKeyDown(KeyCode.Mouse0) && canShoot==true)
{
canShoot=false;
particleSystem.Play();
}
if (targetTime <= 0.0f)
{
canShoot=true;
}
}
void timerEnded()
{
//do your stuff here.
}
}
Hope it works!
In the other answer, you can shoot only once, and then you have to wait. I would create it in a way that you can shoot multiple times and then it overheats. You might need to modify this code and play with the numbers to make it work as you want but that is the idea.
using UnityEngine;
using System.Collections;
public class CoolDownTimer: MonoBehaviour {
public float heat=0.0f;
public bool canShoot=true;
public float heatLimit=10.0f;
Update(){
if(heat > 0f)
heat -= Time.deltaTime;
if(heat < heatLimit)
canShoot = true;
if (Input.GetKeyDown(KeyCode.Mouse0) && canShoot==true)
{
particleSystem.Play();
heat++;
if(heat >= heatLimit){
canShoot=false
}
}
}
}

How to Instantiate circles all over the canvas unity(Mandelbrot set)

i am trying to Make The Mandelbrot set, i have the function thing working, zn = zn^
and i want to Visualizing the Mandelbrot set using circles, i tried this code but it cruses every time i compile, here's the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PaintMand : MonoBehaviour
{
[SerializeField] private GameObject CirclePaint;
[SerializeField] private RectTransform RedCircle;
[SerializeField] private Canvas canvas;
private float sumDistance = 0;
private bool HasFinshed = false;
private Vector2 start = new Vector2(2.133f,0.976f);
private void Update()
{
if (!HasFinshed)
{
sumDistance = AutoAxis.GetSumDistance();
MoveRed();
LoadRed();
}
}
public void MoveRed()
{
if(start.y < -0.988f)
{
HasFinshed = true;
}
else if(start.x <= -2.107f)
{
start.x = 2.133f;
start.y -= 0.20f;
}
else
{
start.x -= 0.20f;
}
RedCircle.anchoredPosition = start;
}
public void LoadRed()
{
if (IsUnstable())
{
GameObject NewCircle = Instantiate(CirclePaint, Vector3.zero,Quaternion.identity);
NewCircle.GetComponent<Image>().color = new Color(sumDistance,sumDistance,sumDistance);
NewCircle.transform.SetParent(canvas.transform);
NewCircle.GetComponent<RectTransform>().anchoredPosition = RedCircle.anchoredPosition;
}
}
private bool IsUnstable()
{
if(sumDistance > 1000)
{
return true;
}
return false;
}
}
the red circle is the c in the equation, zn = zn^ + c
and it moves every frame and checks if its unstable(the autoaxis is the class that makes the Visualizing the function) it gets the sum of the distance between all the circles and sends the float to the paintmad class, this cruses every time, pls help :(

How to make the Spheres able to deal damage to eachother?

Want to make my Spheres able to damage each other
Have tried to get the component of the other object
Health script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class Hitpoints
{
private int health;
public int healthMax;
public Hitpoints(int health)
{
this.health = health;
}
public int GetHealth()
{
return health;
}
public float GetHealthPercent()
{
return (float)health / healthMax;
}
public void Damage(int damageAmount)
{
health -= damageAmount;
if (health < 0)
{
health = 0;
}
}
public void Heal(int healAmount)
{
health += healAmount;
if (health > healthMax)
{
health = healthMax;
}
}
}
Damage script
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class Detect_Blue : MonoBehaviour
{
Hitpoints hitpoints = new Hitpoints(100);
bool onetime = false;
public float radius;
public Vector3 direction = new Vector3(2, 2, 2);
private void Start()
{
Debug.Log("Health: " + hitpoints.GetHealth());
InvokeRepeating("DetectEnemy", 4f, 2f);
}
private void DetectEnemy()
{
var hitColliders = Physics.OverlapSphere(direction, radius);
for (var i = 0; i < hitColliders.Length; i++)
{
if (hitColliders[i].CompareTag("Player"))
{
if (!onetime)
{
onetime = true;
print(hitColliders[i].tag);
InvokeRepeating("Hello", 1, 1);
}
}
// collect information on the hits here
}
}
private void Hello()
{
var hitColliders = Physics.OverlapSphere(direction, radius);
for (var i = 0; i < hitColliders.Length; i++)
{
if (hitColliders[i].CompareTag("Player"))
{
hitColliders[i].GetComponent<Hitpoints>().Damage(10);
}
Debug.Log("Damaged: " + hitColliders[i].GetComponent<Hitpoints>().GetHealth());
if (hitpoints.GetHealth() == 0)
{
Destroy(gameObject);
}
}
}
}
ArgumentException: GetComponent requires that the requested component 'Hitpoints' derives from MonoBehaviour or Component or is an interface.
UnityEngine.Component.GetComponent[Hitpoints] () (at C:/buildslave/unity/build/Runtime/Export/Component.bindings.cs:42)
Detect_Blue.Hello () (at Assets/Detect_Blue.cs:57)
When you do GetComponent<T> on a game object, the type of T should inherit from monobehaviour.(Since Monobehavior are components for game-object, and you are trying to get a component)
To fix this, just simply use the hitpoints you have already created in Detect_Blue.
Debug.Log("Damaged: " + hitColliders[i].GetComponent<Hitpoints>().GetHealth());
will become
Debug.Log("Damaged: " + hitColliders[i].GetComponent<Detect_Blue>().hitpoints.GetHealth());
likewise for hitColliders[i].GetComponent<Hitpoints>().Damage(10);, it should be:
hitColliders[i].GetComponent<Detect_Blue>().hitpoints.Damage(10);
Alternatively,
you can just simply make Hitpoints inherit from Monobehavior and attach the script to the respective gameObject.
Though in your case, the first solution will be more feasible.
Also, you can use OnCollisionEnter to detect when the balls enter collision with another object.

Type `int' does not contain a definition for `Text' and no extension method `Text' of type `int' could be found

Im getting this error in unity, my problem is highscore, it doesnt work. I tried all kinds of videos on youtube but i think im doing something wrong in all of them. Also tried with Text highscore and also doesnt work. It says to me " Are you missing an assembly reference?"
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ScoreScript : MonoBehaviour {
public static int scoreValue = 0;
public Text score;
public static int highscore;
void Start () {
highscore.Text = PlayerPrefs.GetInt("HighScore", 0);
score = GetComponent<Text>();
scoreValue = 0;
}
void Update () {
score.text = "" + scoreValue;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class hazardCollisionFunctions : MonoBehaviour {
private void OnCollisionEnter(Collision col){
if(col.gameObject.tag == "Platform"){
this.gameObject.SetActive(false);
ScoreScript.scoreValue += 1;
}
if(col.gameObject.tag == "Player"){
if(ScoreScript.highscore < ScoreScript.scoreValue){
PlayerPrefs.SetInt("HighScore", ScoreScript.scoreValue);
}
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
}
}
Add a public Text highScoreText; field to your ScoreScript so ScoreScript can work with it.
Set highScoreText.Text to "" + highScore in Start so the text gets set appropriately.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ScoreScript : MonoBehaviour {
public static int scoreValue = 0;
public Text score;
public Text highScoreText;
public static int highscore;
void Start () {
highscore = PlayerPrefs.GetInt("HighScore", 0);
highScoreText.Text = "" + highScore;
score = GetComponent<Text>();
scoreValue = 0;
}
void Update () {
score.text = "" + scoreValue;
}
}
Drag the high score text object into the highScoreText field of the ScoreScript script in the inspector

score not resetting to zero

i'm having problem in the score and high score when i play the game and eat coin its increasing the score and high score but when i die and play again its start counting from the score before i dead like i dead my score was 3 when i play again without closing the game its start counting from 3 and the high score aren't saving
Score Manager script
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class ScoreManager : MonoBehaviour
{
public Text scoreText;
public Text hiScoreText;
public static int scoreCount;
public int hiScoreCount;
public bool scoreIncreasing;
// Use this for initialization
void Start()
{
if (PlayerPrefs.HasKey("HighScore"))
{
hiScoreCount = PlayerPrefs.GetInt("HighScore");
}
}
// Update is called once per frame
void Update()
{
if (scoreIncreasing)
{
scoreCount = BallMain.getPoints();
}
if (scoreCount > hiScoreCount)
{
hiScoreCount = scoreCount;
PlayerPrefs.SetFloat("HighScore", hiScoreCount);
}
scoreText.text = "Score: " + (scoreCount);
hiScoreText.text = "High Score: " + (hiScoreCount);
}
}
BallMain Script
using UnityEngine;
using System.Collections;
public static class BallMain {
private static float ballSpeed = 1.2f;
private static int points;
private static int lives = 0;
public enum BallStateEnum { shielded,Vulnerable};
public static BallStateEnum ballState = BallStateEnum.Vulnerable;
public static float getBallSpeed()
{
return ballSpeed;
}
public static void IncreaseSpeed()
{
ballSpeed += 0.1f;
}
public static void IncreasePoints()
{
points++;
}
public static int getPoints()
{
return points;
}
public static int getLive()
{
return lives;
}
public static void addLife()
{
lives++;
}
}
CoinHandler Script
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class coinHandler : MonoBehaviour {
public Transform particles;
void OnCollisionEnter2D(Collision2D collider)
{
if (collider.gameObject.tag == "Player")
{
Instantiate(particles, new Vector3(transform.position.x, transform.position.y, -0.2f), Quaternion.identity);
BallMain.IncreaseSpeed();
BallMain.IncreasePoints();
GameObject.FindWithTag("CoinUI").GetComponent<Text>().text = BallMain.getPoints().ToString();
Destroy(gameObject);
}
}
BadCoinHandler Script
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;
public class BadCoinHandler : MonoBehaviour {
public Transform particles;
// Use this for initialization
void Start ()
{
Destroy(gameObject, 8f);
}
void OnCollisionEnter2D(Collision2D collider)
{
if (collider.gameObject.tag == "Player")
{
Instantiate(particles, new Vector3(transform.position.x, transform.position.y, -0.2f), Quaternion.identity);
Destroy(gameObject);
if(BallMain.getLive() == 0 && BallMain.ballState == BallMain.BallStateEnum.Vulnerable)
{
SceneManager.LoadSceneAsync(0);
}
}
}
}
You have to zero the score manually. Because you are using the static keyword. So create another void in BallMain and make the point zero; Example:
public static void ResetPoints()
{
points = 0;
}
And call it on awake method on Score Manager script; Example:
void Awake()
{
scoreCount = 0; //Also the score here
BallMain.ResetPoints();
}
To save your high score use this:
PlayerPrefs.SetInt("HighScore",scoreCount);//HighScore is key and scoreCount is the number you want to save
PlayerPrefs.Save();
BTW I thing you need another void to reset ball speed as well.

Categories

Resources