【问题标题】:Why is there no camera attached, even if I've attached it?为什么没有安装相机,即使我已经安装了它?
【发布时间】:2015-09-05 17:51:10
【问题描述】:

所以,我想使用 camera.ViewportToWorldPoint() 来显示我屏幕的 底部中心 边界。因此,我创建了一个脚本,将该组件添加到需要它的对象中。

using UnityEngine;
using System.Collections;

public class PathMovement : MonoBehaviour {

    public Camera cam;
    private Vector3 bound;

    void Awake () {
        cam = GetComponent<Camera> ();
    }

    void Start(){
        bound = cam.ViewportToWorldPoint (new Vector3 (0f, 0.5f));
        Debug.Log (bound);
    }
}

然后,我通过 GUI 附加 MainCamera

然后,当我运行它时,仍然有一个错误说:

MissingComponentException:“RiverPath”游戏对象没有附加“相机”,但 > 脚本正在尝试访问它。 您可能需要将相机添加到游戏对象“RiverPath”。或者您的脚本需要在使用之前检查 > 组件是否已附加。 UnityEngine.Camera.ViewportToWorldPoint(Vector3 位置)(在 C:/buildslave/unity/build/artifacts/generated/common/runtime/UnityEngineCamera.gen.cs:408) PathMovement.Start()(在 Assets/Scripts/PathMovement.cs:21)

这很奇怪,因为我已经连接了主摄像头,但不知何故 unity 没有检测到这一点。我也尝试将cam = GetComponent&lt;Camera&gt;(); 放在Awake()Start() 上,但没有任何效果。 :(

顺便说一句,我正在 Android 上制作移动应用程序。并使用统一 5。

有什么方法可以正确地做到这一点吗? 谢谢。

【问题讨论】:

    标签: c# unity3d camera


    【解决方案1】:

    您将获得MissingComponentException,因为该特定游戏对象没有附加Camera(请参阅异常的描述)。

    您需要知道的是,GetComponent 仅在当前 GameObject 中查找 Component。根据您的 GameObject 层次结构,您可能希望改用 GetComponentInParentGetComponentInChildren

    或者您也可以使用编辑器(拖放)附加相机。如果您在运行时实例化该 Prefab,这可能不起作用,但当它在场景中为静态时应该可以正常工作。

    【讨论】:

    • 是的。我以某种方式拖放相机并随后调用 GetComponent() 。谢谢你
    猜你喜欢
    • 2021-08-18
    • 2019-05-09
    • 2017-04-30
    • 1970-01-01
    • 2011-07-18
    • 1970-01-01
    • 1970-01-01
    • 2022-11-03
    • 1970-01-01
    相关资源
    最近更新 更多