LoginSignup
1
4

More than 5 years have passed since last update.

Unity 時間経過で処理を行う

Posted at

私的メモ。

rendererは古いのでGetComponent<Renderer> ()を使う。

時間経過(何frameか)で処理を変えるにはUpdate()とif文を使えば良い。

using UnityEngine;
using System.Collections;

public class myscript : MonoBehaviour {
    GameObject obj;
    Color c;
    bool flg = false;
    int counter = 0;

    void Update () {
        if (Input.GetMouseButtonDown (0)) {
            Vector3 pos = Input.mousePosition;
            Ray ray = Camera.main.ScreenPointToRay (pos);
            RaycastHit hit;

            if (Physics.Raycast (ray, out hit, 100f)) {
                obj = hit.collider.gameObject;
                c = obj.GetComponent<Renderer> ().material.color;
                obj.GetComponent<Renderer> ().material.color = Color.red;
                counter = 100;
                flg = true;
            }
        }

        // Update()があるのでこのif文はfalseになるまで何度も繰り返される。
        if (flg) {
            Debug.Log (counter);    // counterの値の確認

            if (--counter == 0) {
                flg = false;
                obj.GetComponent<Renderer> ().material.color = c;
            }
        }

    }
}

Update()があるので、if文の条件判定と処理がフレームごとに行われる。上のサンプルではちょうどwhile(true)みたいな処理が行われている。counterの値はデクリメントのおかげで徐々に減少していくのでそのうち処理が行われるようになる。

上のサンプルでは100フレームで処理が行われる。

1
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
4