首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >游戏引擎组件问题

游戏引擎组件问题
EN

Stack Overflow用户
提问于 2017-03-11 17:42:06
回答 1查看 49关注 0票数 0

我目前正在使用C#中的GDI+开发一个游戏引擎。目前,我正在实现组件。组件可以附加到游戏对象上。游戏对象被渲染到显示在窗口/窗体上的屏幕上。

在我继续之前,先看一下GameObject类中的以下几行:

代码语言:javascript
复制
    private List<Component> components = new List<Component>();

    public GameObject()
    {
        AddComponent(new Transform());
    }

    public void Update(GameTime gameTime)
    {
        components.ForEach(c => c.OnUpdate(gameTime));
    }

    public void Render(GraphicsEngine graphicsEngine)
    {
        components.ForEach(c => c.OnRender(graphicsEngine));
    }

    public void AddComponent(Component component)
    {
        component.gameObject = this;
        components.Add(component);
    }

    public T GetComponentOfType<T>() where T : Component
    {
        return (T)GetComponentOfType(typeof(T));
    }

    private Component GetComponentOfType(Type type)
    {
        for (int i = 0; i < components.Count; i++)
            if (components[i].GetType() == type)
                return components[i];

        return null;
    }

    public Transform Transform
    {
        get { return GetComponentOfType<Transform>(); }
    }

现在,希望当我向你展示下一段代码时,事情会变得更清晰一些。

基本上,我有一个从XML文件加载一组游戏对象的方法。但由于某些原因,根据我将精灵组件添加到游戏对象的方式,有时它不能正常工作,并且只有一些精灵渲染到屏幕上

下面是加载游戏对象的方法的部分代码:

代码语言:javascript
复制
 // Creates the object and sets the position
 GameObject obj = new GameObject();
 obj.Transform.Position = new Maths.Vector2(x * map.TileWidth, y * map.TileHeight);

 // This works and renders all sprites to the screen
// obj.AddComponent(new SpriteComponent(sprs[sprID].Bitmap));

// This works and renders all sprites to the screen
// obj.AddComponent(new SpriteComponent());
// obj.GetComponentOfType<SpriteComponent>().Bitmap = sprs[sprID].Bitmap;

 // This doesn't work and only renders some sprites to the screen
 obj.AddComponent(sprs[sprID]);

 // Adds the game object to the screen
 screen.AddGameObject(obj);

为了清楚起见,sprs是sprite组件的列表

任何帮助都是很棒的!

EN

回答 1

Stack Overflow用户

发布于 2017-03-11 23:58:47

好的-最可能的解释是AddComponent在将游戏对象添加到列表之前将它的引用放到了组件中,但我猜您的sprs[]数组构造没有-如果没有所有的代码,就很难判断了。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42733660

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档