Home > Back-end >  I need run add 1 to my var every 1 second in csharp without stopping the program
I need run add 1 to my var every 1 second in csharp without stopping the program

Time:11-05

I want to add 1 to a variable meters when ever 1 seconds passed. Task.Delay wont work for some reason. Here is all my code. Unfortunely im only a beginner at csharp so if you want make you can give me feedback on how to make it better.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class movement : MonoBehaviour
{
    public int movementSpeed = 6;
    private Rigidbody2D rb;
    //the variable i want to add 1 to:
    public int meters;
    public double speeding = 5;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        Ymovement();

        void Ymovement()
        {
            var movement = Input.GetAxis("Vertical");
            transform.position  = new Vector3(0, movement, 0) * Time.deltaTime * movementSpeed;
        }
    }
}  

CodePudding user response:

This is a pretty typical use case for InvokeRepeating:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class movement : MonoBehaviour
{
    public int movementSpeed = 6;
    private Rigidbody2D rb;
    //the variable i want to add 1 to:
    public int meters;
    public double speeding = 5;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        InvokeRepeating("IncreaseMeters", 1f, 1f);
    }

    void Update()
    {
        Ymovement();
    }

    void Ymovement()
    {
        var movement = Input.GetAxis("Vertical");
        transform.position  = new Vector3(0, movement, 0) * Time.deltaTime * movementSpeed;
    }

    void IncreaseMeters()
    {
        meters  = 1;
    }
}  

CodePudding user response:

A Coroutine would help here:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class movement : MonoBehaviour
{
    public int movementSpeed = 6;
    private Rigidbody2D rb;
    //the variable i want to add 1 to:
    public int meters;
    public double speeding = 5;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        YMovement();
        StartCoroutine(IncreaseMeters());
    }

    void YMovement()
        {
            var movement = Input.GetAxis("Vertical");
            transform.position  = new Vector3(0, movement, 0) * Time.deltaTime * movementSpeed;
        }

    IEnumerator IncreaseMeters()
    {
        yield return new WaitForSeconds(1)
        meters  = 1;
    }
}

I also formatted your code a little.

  • Related