在 F# 中运行 Monogame 时出现问题

kio*_*kml 5 .net f# monogame

我正在尝试使用 F#,我想看看是否可以在 F# 中使用 Monogame 做一些简单的事情。我认为从 C# 到 f# 的转换会很简单,但到目前为止还不是这样。到目前为止,我的代码只是一个应该运行的简单的空项目。或者至少在 C# 中是这样。然而在 F# 中运行它会产生

Unhandled exception. System.InvalidOperationException: No Graphics Device Service
Run Code Online (Sandbox Code Playgroud)

我的代码是这样的,它确实没有做任何疯狂的事情。我被迫对 spritebatch 使用可变的 val,因为无论出于何种原因,您都必须在 LoadContent 中实例化它。有人能指出我做错了什么吗?我将不胜感激。

type GameState = 
    inherit Game
    new() =  { inherit Game(); Sb = null;  }
    member this.Gfx : GraphicsDeviceManager = new GraphicsDeviceManager(this)
    val mutable Sb : SpriteBatch 

    override this.Initialize() = 
        this.Content.RootDirectory <- "Content"
        this.IsMouseVisible <- false
        base.Initialize ()

    override this.LoadContent () =
        this.Sb <- new SpriteBatch(this.Gfx.GraphicsDevice)
        base.LoadContent ()

    override this.UnloadContent () = 
        base.UnloadContent ()

    override this.Update (gameTime : GameTime) = 
        base.Update (gameTime)

    override this.Draw (gameTime : GameTime) = 
        this.Gfx.GraphicsDevice.Clear (Color.CornflowerBlue)
        this.Sb.Begin()
        //draw here
        this.Sb.End()
        base.Draw (gameTime)

[<EntryPoint>]
let main argv =
    let gs = new GameState()
    gs.Run()
    0 // return an integer exit code
Run Code Online (Sandbox Code Playgroud)

Mar*_*son 4

阿斯蒂是正确的,你不想GraphicsDeviceManager重复创建一个新的。

这是一些工作代码,对您的代码进行了最小的更改。请注意,要在构造函数时定义值,您需要在()类型名称后面添加。使用mutableforSpriteBatch很丑陋,但在这种情况下很常见,并且您不需要使其成为成员:

open Microsoft.Xna.Framework
open Microsoft.Xna.Framework.Graphics

type GameState() as this = 
    inherit Game()
    let gfx = new GraphicsDeviceManager(this)
    let mutable sb = Unchecked.defaultof<SpriteBatch>

    override this.Initialize() = 
        this.Content.RootDirectory <- "Content"
        this.IsMouseVisible <- false
        base.Initialize ()

    override this.LoadContent () =
        sb <- new SpriteBatch(gfx.GraphicsDevice)
        base.LoadContent ()

    override this.UnloadContent () = 
        base.UnloadContent ()

    override this.Update (gameTime : GameTime) = 
        base.Update (gameTime)

    override this.Draw (gameTime : GameTime) = 
        gfx.GraphicsDevice.Clear (Color.CornflowerBlue)
        sb.Begin()
        //draw here
        sb.End()
        base.Draw (gameTime)

[<EntryPoint>]
let main argv =
    let gs = new GameState()
    gs.Run()
    0 // 
Run Code Online (Sandbox Code Playgroud)

请随意查看我的这个存储库,其中提供了将 MonoGame 与 F# 一起使用的工作示例(尽管现在可能有点过时),包括基本内容管道。