简体   繁体   中英

Unity 3D c# 2 different loops to be run at the same time

So i am creating a very simple game, not going to say what it is about because it is a secret, but i have a variable called "rpm" and every frame, it will rotate an object by "rpm". But every second rpm will increase by 0.1, how would i do that, i have tried using 2 different scripts, and also in the same script using threading, but because i am fairly new to c# i was wondering how i would achieve this, any help is greatly appreciated

script 1

public class Rotate : MonoBehaviour
{
    public float rpm = RPM.rpm;


    // Update is called once per frame
    void Update ()
    {
        transform.Rotate(0, rpm, 0);
    }
}

script 2

public class RPM : MonoBehaviour
{
    public static float rpm = 0.1f;

    void Update()
    {
        System.Threading.Thread.Sleep(1000);
        rpm = rpm + 0.1f;
    }
}

all this does is, not increase the rpm, so it stays the same spin rates, but instead of spinning once every frame it spins every second which i don't want.

Again any help is greatly appreciated, and if you need any extra information just let me know Thanks

Here's a snippet of code that will accomplish what you're asking for

public class RPM : MonoBehaviour
{
    public static float rpm = 0.1f;

    private float elapsed = 0.0f;

    void Update()
    {
        elapsed += Time.deltaTime;
        if (elapsed >= 1.0f) {
            rpm = rpm + 0.1f;
            elapsed = 0.0f;
        }
    }
}

Time.deltaTime is equal to the amount of time that has passed since the last frame of the game (in seconds). The elapsed variable keeps track of how much time has passed simply by adding Time.deltaTime each frame. When the elapsed time is greater than 1 second, your rpm variable gets increased, and the elapsed variable is reset to 0.

I would recommend reading about the different properties of the Time object. You'll probably end up using it a lot.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM