【问题标题】:Cannot convert type 'UnityEngine.Component'无法转换类型“UnityEngine.Component”
【发布时间】:2019-01-30 22:46:48
【问题描述】:

我有一些创建自定义 UI 类的代码。这是通过以下方式完成的:

public class EasyUIData
{
    protected static Canvas EasyCanvasOptions;
    protected static Vector2 EasyCanvasDimensions;
}

public class UIBaseProperties : EasyUIData
{
    protected GameObject UIElement;
    protected RectTransform Anchor;
    protected Vector2 Loc;
    protected int? SizeX, SizeY;

    public UIBaseProperties(Vector2 loc, int? sizeX = null, int? sizeY = null)
    {
        UIElement = new GameObject();
        this.Loc = loc;
        this.SizeX = sizeX;
        this.SizeY = sizeY;
    }
}

public class RawImage : UIBaseProperties
{
    private RawImage UIImageComponent;
    private Texture2D Img;

    public RawImage(Texture2D img, Vector2 loc, int? sizeX = null, int? sizeY = null) : base(loc, sizeX, sizeY)
    {
        UIImageComponent = UIElement.AddComponent(typeof(RawImage)) as RawImage; // this generates the error.
    }
}

但在我想添加RawImage 组件的行中,我收到以下错误:

无法通过引用转换、装箱转换、拆箱转换、包装转换或空类型转换将类型“UnityEngine.Component”转换为“Easy.UI.RawImage”

我不知道为什么,因为我以前使用过这种技术,效果很好。
如果有不清楚的地方请告诉我,以便我澄清。

【问题讨论】:

  • EasyUIData 继承了什么?我认为该对象没有理由能够正确转换为 UnityEngine.Component
  • 您要使用哪种 RawImage? Unity 已经知道名称为 RawImage 的组件。而且您已经建立了自己的同名课程。也许您的班级与 UnityEngine.UI.RawImage 之间存在混淆。
  • @Eliasar EasyUIData 类不继承任何东西,它只是基础。为了清楚起见,我会更新我的问题
  • @GameGenerator 我正在制作一个自定义 UI 框架,它建立在统一的 UI 元素之上。所以我试图在这个自定义 UI 类中使用 Component RawImage。
  • @FutureCake Unity 可能不知道要使用什么原始图像。你想要 UnityEngine.UI.RawImage 但 Unity 理解 Easy.UI.RawImage 这似乎不是组件。

标签: c# unity3d type-conversion components


【解决方案1】:

问题是您将脚本命名为RawImage。将脚本命名为与 Unity 组件相同的名称通常不是一个好主意。

如果您的目标是在您的 RawImage 类中使用 Unity 的 RawImage,则为类名提供命名空间,以便 Unity 不会尝试使用您自己的 RawImage 版本:

替换

private RawImage UIImageComponent;
UIImageComponent = UIElement.AddComponent(typeof(RawImage)) as RawImage;

与:

private UnityEngine.UI.RawImage UIImageComponent;
UIImageComponent = UIElement.AddComponent<UnityEngine.UI.RawImage>();

如果您的目标是使您自己的自定义RawImage 类可用于AddComponentGetComponent 函数,那么您所要做的就是使其派生自MonoBehaviour。由于您自己的RawImage 类派生自另一个类UIBaseProperties,而该类派生自另一个类EasyUIData,因此您必须使最终类派生自MonoBehaviour

public class EasyUIData : MonoBehaviour
{
    protected static Canvas EasyCanvasOptions;
    protected static Vector2 EasyCanvasDimensions;
}

这应该可以解决您的问题,因为使 EasyUIData 派生自 MonoBehaviour 将使您的自定义 RawImage 成为可以附加到游戏对象的组件。

【讨论】:

  • 是的,你完全正确,完全错过了我给他们取同名的事实。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-15
  • 2015-01-26
  • 1970-01-01
相关资源
最近更新 更多