Unity以特定速率保存摄像机图像

时间:2018-04-12 11:51:31

标签: c# unity3d

在我的项目中,我将摄像机图像保存到文件夹,但每秒可节省约60个。我怎样才能将它节省的图像数量减少到每秒10张左右?

void Update()
{ 
    if (TLB)
    {
        DirectoryInfo p = new DirectoryInfo(path);
        FileInfo[] files = p.GetFiles();
        saveFrame(path, "TLB", fileCounter);
        fileCounter = files.Length + 1;
    }
}    

void saveFrame(string path, string type, int counter)
{
    RenderTexture rt = new RenderTexture(frameWidth, frameHeight, 24);
    GetComponentInChildren<Camera>().targetTexture = rt;
    Texture2D frame = new Texture2D(frameWidth, frameHeight, TextureFormat.RGB24, false);
    GetComponentInChildren<Camera>().Render();
    RenderTexture.active = rt;
    frame.ReadPixels(new Rect(0, 0, frameWidth, frameHeight), 0, 0);
    GetComponentInChildren<Camera>().targetTexture = null;
    RenderTexture.active = null;
    Destroy(rt);
    byte[] bytes = frame.EncodeToPNG();
    string filename = path + type + "/" + "/" + frameName(type, counter);
    File.WriteAllBytes(filename, bytes);
}

1 个答案:

答案 0 :(得分:1)

在Unity

中的某个时间间隔后重复执行代码

使用Update()方法:

// Invoke the method after interval seconds
public float interval = 0.1f;

// time counter
float elapsed = 0f;

void Update() 
{
    elapsed += Time.deltaTime;

    // if time is elapsed, reset the time counter and call the method.
    if (elapsed >= interval) 
    {
        elapsed = 0;
        TakeShot();
    }
}

void TakeShot() 
{
   // do your thing here...
}

使用InvokeRepeating()方法:

// Invoke the method after interval seconds
public float interval = 0.1f;

float delaySeconds = 0f; // delay the first call by seconds

void Start()
{
    InvokeRepeating("TakeShot", delaySeconds, interval);
}

void TakeShot() 
{
   // do your thing here...
}

注意:这两种方法都依赖frameratetime-scale

希望这会有所帮助:)