无法更改相机 FOV C#

Zek*_*man 0 c# unity-game-engine

我正在尝试为谷歌纸板制作 VR 游戏,并且我正在尝试在 2 秒后设置相机的 FOV,但是我收到错误:

“NullReferenceException:未将对象引用设置为对象 CameraFOV.Start 的实例”

using UnityEngine;
using System.Collections;
public class CameraFOV : MonoBehaviour
{
    // Use this for initialization
    void Start()
    {
        System.Threading.Thread.Sleep(2000);
        Camera.current.fieldOfView = 60;
    }

    // Update is called once per frame
    void Update()
    {

    }
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*ert 5

使用Camera.main而不是Camera.current. 此外,Unity API 不是线程安全的。你不能像这样暂停主线程。如果您想等待两秒钟,然后将所有摄像机设置为相同的 FOV,那么您可以使用:

void Start()
{
    //This starts the coroutine.
    StartCoroutine(PauseAndSetFOV());     
}

// This is a coroutine.
private IEnumerator PauseAndSetFOV()
{
    // This waits for a specified amount of seconds
    yield return new WaitForSeconds(2f);

    // This sets all the cameras FOV's after waiting two seconds.
    for(int i = 0; i < Camera.allCamerasCount; i++)
    {
        Camera.allCameras[i].fieldOfView = 60;
    }
}
Run Code Online (Sandbox Code Playgroud)

返回的函数IEnumerator是一个协程。这就是在 Unity 中同时执行多项操作的方法。但它不是线程

  • 是的,Unity API 不是线程安全的,这意味着您无法从另一个线程调用 Unity 函数 API 函数。这不是问题,因为您可以在另一个线程中进行一些繁重的计算,然后通知主线程,然后主线程将从 main/Unity 的函数中调用 Unity API 函数。只需告诉他不需要 Thread 即可完成此操作。启动协程,使用“yield return new WaitForSeconds”等待两秒钟,然后运行答案中的当前代码。完毕。无需线程。 (2认同)