【问题标题】:MissingComponentException unity2D缺少组件异常统一 2D
【发布时间】:2016-04-18 19:20:44
【问题描述】:

我无法设置我的相机选项。当我玩游戏并加载另一个场景时,相机选项会发生变化。但是当我为同一个场景点击播放时,它可以正常工作!!!控制台说:

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

您可能需要向游戏对象“Canvas”添加一个相机。或者你的 脚本在使用之前需要检查组件是否被附加。”

这是我当前的脚本:

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;
        }
    }
}

【问题讨论】:

    标签: c# android unity3d unity5


    【解决方案1】:

    没有将相机连接到与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 为相机所附加的GameObject 的名称。

    【讨论】:

      【解决方案2】:

      把你的脚本改成这样:

      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;
              }
          }
      }
      

      然后将场景中的相机附加到此脚本的相机字段。

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          猜你喜欢
          • 2021-02-12
          • 1970-01-01
          • 1970-01-01
          • 2016-02-09
          • 2010-10-17
          • 2020-01-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多