Subtracting Time From Timer In Unity Game C# - c#

Recently, I've been working on a racing game that requires the player to avoid Radioactive Barrels that should subtract 15 seconds if they happen to collide into them; Below is code for my 'Timer' script, and my Barrel Collision Script.
Timer Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Timer : MonoBehaviour
{
public float timeRemaining = 10;
public bool timerIsRunning = false;
public Text timeText;
public void Start()
{
// Starts the timer automatically
timerIsRunning = true;
}
public void Update()
{
if (timerIsRunning)
{
if (timeRemaining > 0)
{
timeRemaining -= Time.deltaTime;
DisplayTime(timeRemaining);
}
else
{
Debug.Log("Time has run out!");
timeRemaining = 0;
timerIsRunning = false;
}
}
}
public void DisplayTime(float timeToDisplay)
{
timeToDisplay += 1;
float minutes = Mathf.FloorToInt(timeToDisplay / 60);
float seconds = Mathf.FloorToInt(timeToDisplay % 60);
timeText.text = string.Format("{0:00}:{1:00}", minutes, seconds);
}
}
Next, is my Barrel Collision Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ExplosionTrigger : MonoBehaviour
{
public AudioSource ExplosionSound;
public ParticleSystem Explosion;
public void OnTriggerEnter(Collider collider)
{
Explosion.Play();
ExplosionSound.Play();
Timer.timeRemaining += 1.0f;
}
}
Is there anyway I could subtract time by colliding into said Barrels from the Timer script?

The easiest way to get the timeRemaining exposed to other classes is using the static keyword.
public static float timeRemaining = 10;
By making the variable static, it can be referenced by other classes. If you would rather not expose the variable completely, you can make static setter/getters. The variable would then be private static float timeRemaining = 10; when using the setter/getter.
public static float TimeRemaining
{
get{ return timeRemaining;}
set { timeRemaining = value;}
}
If you happen to want to expose more variables or methods to your classes from a script, I would recommend either implementing the Singleton Pattern or possibly implement your own Event System which uses the Singleton Pattern to pass events freely in your project. That way, you can subscribe and fire events for various scripts to listen for.

Yes, you could use GetComponent<>() to access the script from a different game object. You should set a GameObject variable, and drag the game object with the script on it. Add this to your barrel script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ExplosionTrigger : MonoBehaviour
{
public AudioSource ExplosionSound;
public ParticleSystem Explosion;
public GameObject Timer;
public float timeLoss;
public Timer timer;
void Start()
{
timer = Timer.GetComponent<TimerScript>();
}
public void OnTriggerEnter(Collider collider)
{
timer.timeRemaining -= 1f;
Explosion.Play();
ExplosionSound.Play();
}
}
You can change the values in the TimerScript using a period. Make sure to change TimerScript to the name of the script on the Timer game object.

Related

How to change a text component to a string in Unity

I am a beginner developer and I am trying to create a timer that shows how many seconds have passed since the start of the game on Unity. I want to change the text component (I am using TextMeshPro to be specific) of the object with the script.
I have been searching on google but nothing has worked yet. I can't find a way to link the public Text to the text component, and I get an error because the text is null.
Well you should reference the text in your code and then change it with a coroutine
public class Timer : MonoBehaviour
{
[SerializeField]
private TMP_Text textComponent;
private int seconds = 0;
private IEnumerator TimeRoutine()
{
while(Application.isPlaying)
{
textComponent.text = seconds.ToString();
yield return new WaitForSeconds(1f);
seconds++;
}
}
private void Start()
{
StartCoroutine(nameof(TimeRoutine));
}
}
Code for Timer with Text mesh pro
using UnityEngine;
using TMPro;
public class Timerexample : MonoBehaviour
{
float cntdnw = 30.0f;
public TMP_Text disvar;
void Update()
{
if(cntdnw>0)
{
cntdnw -= Time.deltaTime;
}
double b = System.Math.Round (cntdnw, 2);
disvar.text = b.ToString ();
if(cntdnw < 0)
{
Debug.Log ("Completed");
}
}
}
Source: Unity timer

I am making a turret but it won't shoot

I am making a turret that shoots a bullet at a set rate, but when the timer is done it doesn't spawn a new bullet even though it doesn't say i have any errors. the bullet has a simple script where it moves at a set speed either left or right, and gets destroyed on impact with an object. the turret does not have a collider right now so I know that's not the problem.
Here is the code for shooting:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TurretShoot : MonoBehaviour
{
public GameObject bullet;
public int bullet_rate = 10;
public int timer;
public Transform SpawnPoint;
void Start()
{
timer = bullet_rate * 10;
}
// Update is called once per frame
void Update()
{
if (timer == 0)
{
Instantiate(bullet, SpawnPoint.transform);
timer = bullet_rate * 10;
}
else
{
timer -= 1;
}
}
}
Here is the bullet code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletMove : MonoBehaviour
{
public int moveDirection;
public int moveSpeed;
void Start()
{
}
// Update is called once per frame
void Update()
{
this.transform.position += new Vector3(moveDirection * moveSpeed, 0, 0);
}
void onCollisionEnter2D(Collider2D col)
{
if (col.GetComponent<Collider>().name != "turret_top")
{
Destroy(this);
}
}
}
Here is the inspector for the turret:
Probably what is happening is it get's destroyed when it spawns.
I don't have a collider on the turret
You aren't instantiating it at the turrent. You are simply setting the parent when you are instantiating it:
public static Object Instantiate(Object original, Transform parent);
Meaning it is probally spawning at Vector3.Zero and instantly gets de-spawn.
Rather use the overload method of:
public static Object Instantiate(Object original, Vector3 position, Quaternion rotation);
That way you are spawning it the location you want. This is how you would go about it:
var bulletObj = Instantiate(bullet, SpawnPoint.transform.position, Quaternion.Identity);
bulletObj.transform.parent = SpawnPoint.transform;
timer = bullet_rate * 10;

my variable doesn't change even that in the log its say the variable change [unity]

I have 1 script to PlayerMovement and one for powerUp I the power-up code I reference player movement to change the speed and change the bool named timer to true and I write that in log and when I touch the paper the speed doesn't change and the timer don't turn to true but in the log, its say that is yes
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
private float TargetPos;
public float Speed;
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.position = new Vector2(TargetPos, transform.position.y);
}
public void right()
{
TargetPos = transform.position.x + Speed * Time.deltaTime;
}
public void left()
{
TargetPos = transform.position.x - Speed * Time.deltaTime;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Powrups : MonoBehaviour
{
public PlayerMovement pm;
public float PowerUpActiveTime;
public float StartPowerUpActiveTime;
public float peperSpeed;
float NormalSpeed;
bool timer;
bool timerover;
private void OnTriggerEnter2D(Collider2D col)
{
if (col.name == "peper")
{
pm.Speed = peperSpeed;
timer = true;
Debug.Log("timerOn");
Debug.Log(pm.Speed);
Debug.Log(timer);
}
}
private void Update()
{
while(timer)
{
GameObject Pause = GameObject.Find("Pause");
PauseScript pausescript = Pause.GetComponent<PauseScript>();
if (!pausescript.pause)
{
PowerUpActiveTime -= Time.deltaTime;
if(PowerUpActiveTime <= 0 )
{
timerover = true;
}
if (timerover)
{
timer = false;
}
}
}
if (timerover)
{
PowerUpActiveTime = StartPowerUpActiveTime;
pm.Speed = NormalSpeed;
}
}
private void Start()
{
PowerUpActiveTime = StartPowerUpActiveTime;
timerover = false;
NormalSpeed = pm.Speed;
}
}
Your mistake is that while loop.
You are lucky that until now you probably have tested this always while not being in pause mode ;)
This while would completely freeze your app and the entire Unity Editor!
In general be extremely careful with while loops and nested conditions like here, where the exit condition might never be fulfilled!
What happens currently is that you are not in pause mode so this while loop gets activated and runs until timer is set to false .. completely within one single frame. That is the reason why to you it seems that the value is never true.
What you rather want anyway is that code block be executed once per frame.
And in particular in a frame based application like Unity also have some performance impacts in mind.
You shouldn't use Find and GetComponent repeatedly within Update but store and re-use the results.
So your code should rather be
// If possible already drag this in via the Inspector
[SerializeField] private PauseScript _pauseScript;
private void Start()
{
PowerUpActiveTime = StartPowerUpActiveTime;
timerover = false;
NormalSpeed = pm.Speed;
// Get this ONCE as fallback on runtime
if(!_pauseScript)
{
_pauseScript = GameObject.Find("Pause"). GetComponent<PauseScript>();
// Or simply use
//_pauseScript = FindObjectOfType<_pauseScript>();
}
}
private void Update()
{
if(timer)
{
if (!_pauseScript.pause)
{
PowerUpActiveTime -= Time.deltaTime;
if(PowerUpActiveTime <= 0 )
{
timer = false:
PowerUpActiveTime = StartPowerUpActiveTime;
pm.Speed = NormalSpeed;
}
}
}
}
Besides all that, you should rather not let an external power-up control your player values. I would rather go the other way round and have your player object have a component which checks into which power-up items you run and react to it accordingly.
So your power-up itself would actually only be a trigger without any clue if or how exactly the player will be influenced by it.

Unity problem activating a function with parameters in camera from another script in GameObject Enemy

I have a script that makes the camera do a shake by putting a button because
It is a public access function, if I do it that way when placing a button it works well but what I cannot achieve is to call the function so that every time my player collides with an enemy he makes the shake. I hope you can help me.
The shake code in camera is:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ScreenShaker : MonoBehaviour {
private float shakeAmount = 0.5f;
private float shakeTime = 0.0f;
private Vector3 initialPosition;
private bool isScreenShaking = false;
void Update () {
if(shakeTime > 0)
{
this.transform.position = Random.insideUnitSphere * shakeAmount + initialPosition;
shakeTime -= Time.deltaTime;
}
else if(isScreenShaking)
{
isScreenShaking = false;
shakeTime = 0.0f;
this.transform.position = initialPosition;
}
}
public void ScreenShakeForTime(float time)
{
initialPosition = this.transform.position;
shakeTime = time;
isScreenShaking = true;
}
}
The enemy code is:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ControladorEnemigoCirculoMediano : MonoBehaviour
{
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{
Here I don't know what to call the public void function ScreenShakeForTime (float time);
I already tried many things online but when my character comes into contact with the character, I don't do the shake in the camera.
}
}
}
You can create Unity-singleton in your ScreenShaker class like:
class ScreenShaker
{
public static ScreenShaker Instance {private set; get;};
void Awake() {
Instance = this;
}
}
And than from any place to call like:
ScreenShaker.Instance.ScreenShakeForTime(2f);
This is the easiest way, but maybe it's better to create standard singeleton(it's up to you).
And also don;t forget to destroy it on OnDestroy()
can you tell me in enemy game object collider isTrigger is enable or not
if it is not enable then use OnColliderEnter2D(Collision2D other){} for collision detection

Unity Highscore reset at respawn

I'm trying to be able to respawn as well as reset the score counting as soon as i walk into my "Gold" Object.
As for now i'm not even able to respawn which was possible earlier before trying to implement the "Score-Stuff" (at first the "FoundGold" Script was only used to be able to respawn). Also i'm trying to make the lowest Score the High-Score.
Note that im new to C# and i kinda put everything together from the tutorials i needed so a answer with some actual code/stating where something went wrong would be much appreciated.
//GoldFound Code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GoldFound : MonoBehaviour
{
private ScoreManager theScoreManager;
public Transform target;
[SerializeField] private Transform player;
[SerializeField] private Transform respawnpoint;
private void Start()
{
theScoreManager = FindObjectOfType<ScoreManager>();
}
private void OnTriggerEnter(Collider other)
{
theScoreManager.scoreIncreasing = false;
player.transform.position = respawnpoint.transform.position;
theScoreManager.scoreCount = 0;
theScoreManager.scoreIncreasing = true;
}
}
other code
//ScoreManager
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ScoreManager : MonoBehaviour
{
public Text scoreText;
public Text hiScoreText;
public float scoreCount;
public float hiScoreCount;
public float pointPerSecond;
public bool scoreIncreasing;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
if (scoreIncreasing)
{
scoreCount += pointPerSecond * Time.deltaTime;
}
if(scoreCount > hiScoreCount)
{
hiScoreCount = scoreCount;
}
scoreText.text = "Score: " + Mathf.Round (scoreCount);
hiScoreText.text = "High Score: " + Mathf.Round (hiScoreCount);
}
}
If you want to save your highscore in-between play sessions, then the easiest way to do so is to save the value to PlayerPrefs. If you want to start saving more / more complex stuff you really should save it in a file you generate yourself. But in your case, PlayerPrefs is fine.
Here's a Unity tutorial on the subject:
https://unity3d.com/learn/tutorials/topics/scripting/high-score-playerprefs
Otherwise, you can just do it like this:
public void SetHighscore (float currentScore)
{
if (PlayerPrefs.HasKey("highscore"))
{
float highscore = PlayerPrefs.GetFloat("highscore");
if (highscore > currentScore)
{
PlayerPrefs.SetFloat("highscore", currentScore);
PlayerPrefs.Save();
}
}
else
{
PlayerPrefs.SetFloat("highscore", currentScore);
PlayerPrefs.Save();
}
}
Then just write PlayerPrefs.GetKey("highscore") whenever you need it.
(Though I'd also recommend you check if it exists by using the PlayerPrefs.HasKey("highscore"))
https://docs.unity3d.com/ScriptReference/PlayerPrefs.html

Categories

Resources