Increase value by one each second [C#]
Hello, I'd like to increase a variable's value by one each time, I've looked everywhere and I've only seen it in JS but I can't seem to find any for C# and I can't translate JS-C# very well. If someone could teach me how to increase a value by one each second or tell me how to do it that'd be great!
Because I'm actually stuck on this.
Answer by arain55 · Nov 05, 2016 at 10:23 PM
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class random : MonoBehaviour {
float foo;
float valueToIncreaseEverySec;
void Start ()
{
}
void Update()
{
foo += valueToIncreaseEverySec * Time.deltaTime;
}
}
alright I'll explain what this does, the variable foo is just any old variable and the variable valueToIncreaseEverySec is the value you want foo to increase by, and in the update method the line is essentially saying, plus valueToIncrease * Time.deltaTime to foo, Time.deltaTime is the time between each frame you need this so it can plus the value according to unity, without things become crazy.
Thanks! Found a way using WaitForSeconds to do it on my own but I tried this on a separate project and all the other answers and this one worked great! + the explanation! Thanks for the great answer!
Answer by Cynikal · Nov 05, 2016 at 09:09 PM
float _t = 0f;
void Update()
{
_t += Time.deltaTime;
if (_t >= 1f)
{
_t = 0f;
WhateverVariableToIncrement++;
}
}
or:
void IncrementByOne()
{
MyVariable++;
}
void Start()
{
InvokeRepeating("IncrementByOne", 1f, 1f);
}
Answer by Niko098 · Nov 05, 2016 at 10:24 PM
It should work like this: using UnityEngine; using System.Collections;
public class NameScript : MonoBehaviour { public int MyInt; private float timer;
void Update()
{
timer += Time.deltaTime;
if (timer > 1f)
{
MyInt++;
Debug.Log (MyInt);
timer = 0f;
}
}
}
Your answer
Follow this Question
Related Questions
Changing a variable value 2 Answers
Change a variable value for 5 seconds 1 Answer
Strange behavior using structs with HashSet 0 Answers
Change in Editor via Script Values of another Script 2 Answers