无法转换类型'UnityEngine.Component'

Fut*_*ake 2 c# components type-conversion unity-game-engine

我有一些代码可以创建自定义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.
    }
}
Run Code Online (Sandbox Code Playgroud)

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

无法通过引用转换,装箱转换,拆箱转换,换行转换或空类型转换将类型'UnityEngine.Component'转换为'Easy.UI.RawImage'

我不知道为什么,因为我曾经使用过这种技术,它工作得很好.
如果有什么不清楚请告诉我,所以我可以澄清.

Pro*_*mer 6

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

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

更换

private RawImage UIImageComponent;
UIImageComponent = UIElement.AddComponent(typeof(RawImage)) as RawImage;
Run Code Online (Sandbox Code Playgroud)

有:

private UnityEngine.UI.RawImage UIImageComponent;
UIImageComponent = UIElement.AddComponent<UnityEngine.UI.RawImage>();
Run Code Online (Sandbox Code Playgroud)

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

public class EasyUIData : MonoBehaviour
{
    protected static Canvas EasyCanvasOptions;
    protected static Vector2 EasyCanvasDimensions;
}
Run Code Online (Sandbox Code Playgroud)

这应该可以解决您的问题,因为EasyUIData从中派生MonoBehaviour将使您的自定义RawImage成为可以附加到GameObject的组件.