Unity Slider decrease as timer - c#

I'm trying to make a countdown timer but using a Unity Slider instead of text but I've ran across a few issues. So my current code is:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class CountdownTimer : MonoBehaviour {
//public Text timeText;
public float startingTime = 100.0f;
public Slider Timer;
// Use this for initialization
void Start () {
Timer = GetComponent<Slider> ();
}
// Update is called once per frame
void Update () {
startingTime -= Time.deltaTime;
Timer.value = startingTime;
if (startingTime <= 0)
{
startingTime = 0;
Application.LoadLevel ("GameOver");
}
}
}
This code works if I were to replace the slider with the text but not vice versa. My second issue is when I attach this code to my player and link the slider from the hierarchy, it disappears when I start the game.
Last issue is when I try to add an On Value Changed, I can link it to my player to get the functions from the code but from doing my research there isn't really anything I can link it to since I only have start and update. Scrollbars can use private voids and receive the dynamic float that way but I haven't been able to yet with Sliders
Example:
On Change Value

It does not work on the slider you say, you need to pass the max value as 100 on the slider component, or it uses 1 until the value gets between 0 and 1.
A UI item has to be under a Canvas to be rendered, so attaching it to your player makes it discarded from rendering. You can put the Canvas with the slider as child under the player object. But I would keep the canvas separated for clarity(POV).
The picture you added shows that you passed an object, but now you need to assign a method. Click the No Function and it will display all the available methods.

Related

How to make a non-UI countdown in Unity?

I'm trying to make a countdown attached to a sprite. The countdown will count down from 10 to zero, and won't be attached to the Canvas, so it won't be static on the screen. All of the tutorials for something like this have been for UI and don't allow 3D text. Anyone have any ideas on how to do this?
There are two ways to do this:
Use UI elements on a separate canvas set to World Space
Use the TextMesh element to put a 3D mesh of text in the world
I don't really know the pros and cons of each approach so go with whichever is easier for you to implement and keep the other in mind if you run into problems.
If you're looking for a detailed tutorial, anything explaining how to do popup damage numbers will be the same method, just with a different script telling it what text to display. There are a few good tutorials on the top of the YouTube results.
As for the countdown script, it's fairly simple.
//put this script on a GameObject prefab with a TextMesh component, or a canvas element
public class Countdown : MonoBehaviour
{
public TextMesh textComponent; //set this in inspector
public float time; //This can be set in inspector for this prefab
float timeLeft;
public void OnEnable()
{
textComponent = GetComponent<TextMesh>(); //in case you forget to set the inspector
timeLeft = time;
}
private void Update()
{
timeLeft -= Time.deltaTime; //subtract how much time passed last frame
textComponent.text = Mathf.CeilToInt(timeLeft).ToString(); //only show full seconds
if(timeLeft < 0) { gameObject.SetActive(false); } //disable this entire gameobject
}
}

Unity 5 - Adding a Pre-made Countdown Timer C# Script to the Game Scene as a Text UI Element

Hello I am currently Devolping a Game Scene and require a countdown timer to appear in the top left corner of the screen as a text UI element. I already have a script prepared and simply need to add the component to the game scene.
I have created a text object (called CountdownTimer) in the canvas section of my hierarchy. Created a blank game object, added the script as a component and have added the relevent text object where asked for
Alas this has not worked and I'm unsure why but I believe it to be the way the text object is set up or the way in which I have called upon my script
Here's the relevent C# code:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System;
public class CountdownTimer : MonoBehaviour {
public int maxCountDownTimeLeftInSecond = 15;
public Text Text_Countdown_Timer = null;
public static double secondsLeft = 0.0;
DateTime GameStartDateTime;
void Start ()
{
GameStartDateTime = DateTime.Now;
}
void FixedUpdate ()
{
TimeSpan currentTimeLeft = DateTime.Now - GameStartDateTime;
secondsLeft = maxCountDownTimeLeftInSecond -
currentTimeLeft.TotalSeconds;
if (secondsLeft > 0)
{
Text_Countdown_Timer.text = "Time Left: " + string.Format ("
{0:0.00s", secondsLeft);
} else {
Text_Countdown_Timer.text = "Time Left: 0.00s";
}
}
}
I appologise if this is a simple question and I'm missing something very obvious but any help is much appriciated. Thank you
Are you saying the code isn't working or the text object doesn't show up in your game? If it is the latter, this could have to do with the layer. If it is at the same depth as the background, it won't show up. Try bringing it up a bit.

How to make score appear on GUI?

I'm making a game, and I'm having trouble making the score appear on the game.
So far, this is all I have:
public class keepingScore : MonoBehaviour {
public static double homeScore;
// Use this for initialization
void Start ()
{
double homeScore = 5.0;
print(homeScore);
}
}
So my code is printing 5 to the console, and when I've tried other methods, it says it wont work because homeScore is not a string.
Any help guys?
Thanks!
Please try use GUI:
https://docs.unity3d.com/ScriptReference/GUI.html
or you can try Canvas GUI that must better:
https://docs.unity3d.com/Manual/UICanvas.html
So first of all what you need if you want to have score in your GUI is to have a Text component in your scene.
Once you have your Text component in your scene you need to create a script that will handle the score and add it to the Text component you have created. This is an example of a Score manager script:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class keepingScore : MonoBehaviour {
public static double homeScore;
Text text;
void Awake () {
text = GetComponent<Text>();
homeScore = 0.0;
}
// Update is called once per frame
void Update () {
text.text = "Score: " + homeScore;
}
}
Now you can attach this script to the Text component you have created earlier. What this script does is first retreive the Text component that it is attached too and initialize a public static double homeScore that you can access and modify from any script by just doing keepingScore.homeScore. Finally the Update function will run every frame to update the Text component you have.
Now that you have a Text component in your scene with this script attached to it, you can start modifying the value of your score. From wherever you want. An example would be let's say when your player picks up a coin you want to give him 1 point, so if the player collides with the coin you add 1 to the homeScore
void OnCollisionEnter(Collision collision) {
if (collision.CompareTag("Coin"))
keepingScore.homeScore++;
}
This would for example add 1 to the score when the player collides with the coin.
You can do keepingScore.homeScore += pointAmount wherever you want to add points to the player and it will automatically update the GUI Text.

Unity slider controlling animation

I'd like to create a slider that displays the current frame of an animation within unity, and when you move the slider it updates the current frame within the animation.
So far I have (edited code)
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class NewAnimController : MonoBehaviour {
public Slider sliderScrubber;
public Animator animator;
void Start()
{
float t = animator
.GetCurrentAnimatorStateInfo(0)
.normalizedTime;
//animator.speed = 0.0001f;
//slider.onValueChanged.AddListener(OnValueChanged);
}
public void Update()
{
float animationTime = animator.GetCurrentAnimatorStateInfo(0).normalizedTime;
Debug.Log("animationTime (normalized) is " + animationTime);
sliderScrubber.value = animationTime;
}
public void OnValueChanged(float changedValue)
{
animator.speed = 0.0001f;
animator.Play("Take 001", -1, sliderScrubber.normalizedValue);
}
}
At the moment this changes the current frame in the animation when you adjust the slider, but when the animation is played, the slider doesn't update.
How can I get this to work in both directions?
Many thanks
First be sure to delete all code lines
animation.speed = 0.0001f
which appear to be leftover from a tutorial or debugging.
What about
public void Update()
{
float animationTime = animator.GetCurrentAnimatorStateInfo(0).normalizedTime;
// in case of a looping anime, animationTime = animationTime %1f;
Debug.Log("animationTime is " + animationTime);
// of course remove that in production
slider.value = animationTime;
}
Note of course set the scrubber min/max to 0f, 1f in the editor.
Note, you may prefer to make a "scrubber" for a joint position; also works nice.
Note, subtle issue: experienced programmers may prefer to set the animation speed to zero, while the user's finger is holding down the slider; probably OK without doing this.
NOTE take care to delete all references to animation.speed. It apears to be a carry-over from an incorrect tutorial.
Ok, so after much throwing things around to see what sticks, this is giving me the result I'm after.
I'd like to thank #JoeBlow for all his help.
Somebody buy that guy a drink.
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class NewAnimController : MonoBehaviour {
public Slider sliderScrubber;
public Animator animator;
public void Update()
{
float animationTime = animator.GetCurrentAnimatorStateInfo(0).normalizedTime;
Debug.Log("animationTime (normalized) is " + animationTime);
sliderScrubber.value = animationTime;
}
public void OnValueChanged(float changedValue)
{
animator.Play("Take 001", -1, sliderScrubber.normalizedValue);
}
}
I will update this again when I have a play pause button working and a slider that can change the speed of playback.
I think you almost got it just instead of assigning the value directly in the update function:
sliderScrubber.value = animationTime;
Use this:
sliderScrubber.Set(animationTime, false);
the false parameter is to call the OnValueChange() function in your case you don't want that.
Addionally you can check if the animation is being played to avoid unnecesary calls to the Set function:
http://answers.unity3d.com/questions/362629/how-can-i-check-if-an-animation-is-being-played-or.html
and check your slider.maxValue to adjust it to the animation length.

Unity3d progress bar

I am developing a game using unity3D and I need help making a progress time bar such that on collecting particular items time is added and thus the game continues.
Create a UI Image that is of type Filled. Use horizontal or vertical fill depending on your progress bar. Then from inside a script you can manipulate the value of the image. I will give you a very simple c# example. For the rest you can just use google and read the unity scripting API.
public class Example: MonoBehaviour {
public Image progress;
// Update is called once per frame
void Update ()
{
progress.fillAmount -= Time.deltaTime;
}
}
U could use a slider en slider.setvalue.
Example:
//to use this add first a slider to your canvas in the editor.
public GameObject sliderObject; //attachs this to the slider gameobject in the editor or use Gameobject.Find
Slider slider = sliderObject.GetComponent<Slider>();
float time;
float maxtime; //insert your maxium time
void start(){
slider.maxValue = maxtime;
}
void update()
{
time += Time.deltaTime;
if (time < maxtime)
{
slider.value = time;
}
else
{
Destroy(sliderObject);
//time is over, add here what you want to happen next
}
}

Categories