繁体   English   中英

MissingComponentException unity2D

[英]MissingComponentException unity2D

我无法设置相机选项。 当我玩游戏并加载另一个场景时,相机选项也会更改。 但是当我在同一场景中播放时,它可以正常工作!!! 控制台说:

MissingComponentException:在“画布”游戏对象上没有附加“相机”,但是脚本正在尝试访问它。

您可能需要将相机添加到游戏对象“画布”。 或者您的脚本需要在使用组件之前检查组件是否已连接。”

这是我当前的脚本:

using UnityEngine;
using System.Collections;

public class PixelPerfectCamera : MonoBehaviour {

    public static float PixelsToUnits = 1f;
    public static float scale = 1f;

    public Vector2 nativeResolution = new Vector2(400, 160);


    void Awake()
    {

         var camera =  GetComponent<Camera>();


        if (camera.orthographic)
        {
            scale = Screen.height / nativeResolution.y;
            PixelsToUnits *= scale;
            camera.orthographicSize = (Screen.height / 2.0f) / PixelsToUnits;
        }
    }
}

没有将摄像机连接到PixelPerfectCamera脚本所连接的同一PixelPerfectCamera

如果场景中只有一台摄像机,请更改

var camera =  GetComponent<Camera>(); 

Camera camera = Camera.main; //Use the main camera

如果场景中有多台摄像机,请使用:

Camera camera = GameObject.Find("NameOfGameObjectCameraIsAttachedTo").GetComponent<Camera>(); //Use the main camera

您必须更改 NameOfGameObjectCameraIsAttachedTo到相机连接到游戏对象的名称。

将脚本更改为此:

using UnityEngine;
using System.Collections;

public class PixelPerfectCamera : MonoBehaviour {

    public static float PixelsToUnits = 1f;
    public static float scale = 1f;

    public Vector2 nativeResolution = new Vector2(400, 160);
    public Camera camera;

    void Awake()
    {
        if (camera.orthographic)
        {
            scale = Screen.height / nativeResolution.y;
            PixelsToUnits *= scale;
            camera.orthographicSize = (Screen.height / 2.0f) / PixelsToUnits;
        }
    }
}

然后将场景中的摄像机附加到此脚本的“摄像机”字段。

您可能需要看看RequireComponent,它不是必需的,但是对于此类问题有很大帮助。 http://docs.unity3d.com/ScriptReference/RequireComponent.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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