2016-12-02 5 views
0

私は公式のドキュメントからMonoGameを学ぼうとしています。GraphicsDeviceのメソッドを使用できません

しかし、私はぶつかり合った。そのコードでは

、彼らは次のことをやった...今

Vector2 playerPosition = new Vector2(GraphicsDevice.Viewport.TitleSafeArea.X, 
GraphicsDevice.Viewport.TitleSafeArea.Y + GraphicsDevice.Viewport.Height/2); 

、私は取得しています問題は、このです。私は、コードGraphicsDevice.Viewportのビットを使用するたびに、MonoGameはそれを許可し、次のエラーを与えていない:

An object reference is required for the non-static field, method or property 'GraphicsDevice.Viewport'

が、私はこのエラーを修正するために何ができますか?

答えて

1

これは実際にMonoGameの問題ではありません。 C#がプロパティと型を解決する方法と関係があります。 を見ると、それはGraphicsDeviceクラスのの非スタティックプロパティであることがわかります。

public class GraphicsDevice 
{ 
    public Viewport Viewport { get; set; } 
} 

このパズルのもう一つの部分は、GraphicsDevice property on the Game classです。

public class Game 
{ 
    public GraphicsDevice GraphicsDevice { get; } 
} 

これが意味することは、あなたがGameクラスのコンテキスト内で行GraphicsDevice.Viewportを使用する場合、それはあなたがGameクラスのコンテキスト外にそれを使用するときに異なる意味を持っていることです。

たとえば、Gameから派生したクラスのUpdateメソッドの内部にコードを挿入すると、そのコードが機能します。それは、この文脈で基本GameクラスからGraphicsDeviceプロパティを使用しているため

public class Game1 : Game 
{ 
    public void Update(GameTime gameTime) 
    { 
     Vector2 playerPosition = new Vector2(GraphicsDevice.Viewport.TitleSafeArea.X, GraphicsDevice.Viewport.TitleSafeArea.Y + GraphicsDevice.Viewport.Height/2); 
    } 
} 

この作品の理由は、あります。

一方、GraphicsDeviceプロパティを持たないクラスの中に同じコードを置くと、あなたの質問にエラーが発生します。

public class MyClass 
{ 
    public void Update(GameTime gameTime) 
    { 
     Vector2 playerPosition = new Vector2(GraphicsDevice.Viewport.TitleSafeArea.X, GraphicsDevice.Viewport.TitleSafeArea.Y + GraphicsDevice.Viewport.Height/2); 
    } 
} 

私は、そのようなものだと思われますが、あなたの質問の限られた情報では分かりづらいです。

この問題を解決するには複数の方法があります。 1つの方法は、カスタムクラスのコンストラクタにGraphicsDeviceを挿入して代わりに使用することです。

public class MyClass 
{ 
    private GraphicsDevice _graphicsDevice; 

    public MyClass(GraphicsDevice graphicsDevice) 
    { 
     _graphicsDevice = graphicsDevice; 
    } 

    public void Update(GameTime gameTime) 
    { 
     Vector2 playerPosition = new Vector2(_graphicsDevice.Viewport.TitleSafeArea.X, _graphicsDevice.Viewport.TitleSafeArea.Y + _graphicsDevice.Viewport.Height/2); 
    } 
} 

私は役立つことを望みます。

関連する問題