ApachePilotMPE
ApachePilotMPE

Reputation: 193

Can you add a texture to an XNA project with code?

I've been trying to develop games recently, so I've just started learning XNA today, after finally throwing in the towel on a WinForms game. So, I know that you are SUPPOSED to load textures in using the Visual Studio solution explorer, but is there any way to do that with a line of code, something akin to Game.LoadTexture(string filename); or something like that? Because I prefer to do everything from the code to keep it all straight.

Upvotes: 2

Views: 108

Answers (1)

davidsbro
davidsbro

Reputation: 2758

If you are using XNA 3.1 or earlier, you could look at Texture.FromFile (see here). This method works with 1D, 2D, and 3D textures, and should be used in the LoadContent method.

However, if you are using XNA 4.0, there is no Texture.FromFile method. Instead, there's Texture.FromStream (I don't think there's a FromStream method for a Texture3D or Texture though). You could create a method to load a texture (in this case, a Texture2D) from a file: (code from here)

private Texture2D TextureFromFile(string path)  
{  
    FileStream fs = new FileStream(path, FileMode.Open);  
    Texture2D t2d = Texture2D.FromStream(GraphicsDevice, fs);  
    fs.Close();  
    return t2d;  
} 

Also see here and here for more info, especially the latter for getting a texture or Texture3D from a file. HTH

Upvotes: 3

Related Questions