即時通訊既是新的網站,也是編程的新手。我最近一直在努力學習新技能,以幫助更好地組織/管理我的代碼,並使其更高效,可讀和容易。界面 - 拋出空的異常
好吧好吧,我不會去太多的是,我遇到的問題是在XNA 3.1,我使用C#表達08.
我有一個名爲InputHandler一個自包含遊戲conponent,更新在基本循環(Game1)之後進行循環,到目前爲止只是檢查鍵盤輸入並將結果存儲到具有Get屬性的KeyboardState實例中 - 唯一的其他代碼實際上是在退出Game1時,如果按Esc鍵,用於存儲輸入之後。
代碼:
private KeyboardState keyboardstate;
public KeyboardState Keyboard_State
{
get { return (keyboardstate); }
}
public override void Update(GameTime gameTime)
{
keyboardstate = Keyboard.GetState();
if (keyboardstate.IsKeyDown(Keys.Escape))
Game.Exit();
base.Update(gameTime);
}
移動到該問題,另一個遊戲conponent稱爲相機嘗試經由IInputHandler的實例訪問InputHandler的Keyboard_State屬性(這是順便說一句的界面)
public interface IInputHandler
{
KeyboardState Keyboard_State { get; }
}
毫無疑問,這個接口是在InputHandler組件中實現的。移動到錯誤,以及我在我的更新循環內的相機組件一些邏輯代碼,它試圖通過接口訪問Keyboard_State屬性,檢查一些條件,然後改變相機apropriatly。
private IInputHandler input;
以下代碼位於相機組件內的無效更新循環內。
if (input.Keyboard_State !=null)
{
if (input.Keyboard_State.IsKeyDown(Keys.Left))
cameraYaw += spinRate;
if (input.Keyboard_State.IsKeyDown(Keys.Right))
cameraYaw -= spinRate;
if (cameraYaw > 360)
cameraYaw -= 360;
else if (cameraYaw < 360)
cameraYaw += 360;
}
我在*得到一個空引用異常,如果(input.Keyboard_State!= NULL)*線,抱怨說這不是一個實例。
我是新來的Interfaces,直到我開始嘗試學習XNA並且開始學習關於組件,最終我想創建基本組件來管理3D遊戲(沒有花哨,只是有組織和管理)。
任何幫助,將不勝感激。謝謝:)
*其它信息*
我的相機建築工是:
public Camera(Game game)
: base(game)
{
graphics = (GraphicsDeviceManager)Game.Services.GetService(typeof(IGraphicsDeviceManager));
input = (IInputHandler)game.Services.GetService(typeof(IInputHandler));
}
和我InputHandler建築工是空的,我的Game1建築工是:
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
camera = new Camera(this);
Components.Add(camera);
input = new InputHandler(this);
Components.Add(input);
input.UpdateOrder = 0;
camera.UpdateOrder = 1;
// this component alows Asyncroniously save/load game.
Components.Add(new GamerServicesComponent(this));
#if DEBUG
fps = new FPS(this);
Components.Add(fps);
fps.UpdateOrder = 1;
camera.UpdateOrder = 2;
#endif
}
輸入輸入處理程序遊戲組件的一個實例。
private InputHandler input;
希望這有助於:)
KeyboardState是一個結構,而不是一個類!不需要測試null(永遠不會!)。但是,您應該像第一個示例中那樣進行初始化,因爲與類不同,可以在不使用新運算符的情況下實例化結構,但這些字段將保持未分配狀態,並且只有在初始化所有字段之後才能使用該var。 – Steve 2012-03-24 18:09:44