I’m trying to make my game load compiled xnb textures outside the main game class, as I usually do with my image files (which are not compiled to xnb format) and it doesn’t work.
Texture2D.FromStream returns “unexpected error”, and
using (var g = new Game1())
{
Texture2D t2d = g.Content.Load<Texture2D>(file);
}
says that the file doesn’t exist, while File.Exists right next to it shows that it indeed exists.
I can’t add those xnb files to my project, because I won’t have them at compile time. How do I solve this?
More code:
public void LoadXNA(Microsoft.Xna.Framework.Content.ContentManager cmgr, string path)
{
string xnaTexturesPath = path.Substring(0, path.LastIndexOf("\\")) + "\\textures xna";
if (Directory.Exists(xnaTexturesPath))
{
var files = Directory.GetFiles(xnaTexturesPath, "*.xnb");
foreach(var file in files)
{
string filename = Path.GetFileNameWithoutExtension(file);
string ext = Path.GetExtension(file);
string pathNoext = file.Replace(ext, "");
var t2d = cmgr.Load < Texture2D > (pathNoext);
}
}
}
First of all, you do not need an entire
Game. All you need is aGraphicsDevice. Note that the textures are bound to the graphics device – so it must remain in existence while the textures do – and textures cannot be shared between multiple devices.To get a
ContentManagerwithout aGameclass, have a look at the XNA WinForms Sample. In particular, it shows how to create aGraphicsDevicebound to a given control (which can be aForm– you can make it a hidden one if you don’t need to use it otherwise), how to make a service provider and put aIGraphicsDeviceServicein it, and then how to create aContentManagerusing that service provider.Alternately, have a look at this answer which provides some code which you can just use directly (it makes use of some classes in that same WinForms sample). It’s XNA 3.1, so it may require minor tweaks for 4.0, but should generally work.
Texture2D.FromStreamcannot load XNB files. XNB files need to be run throughContentManagerto basically “unwrap” all the XNB stuff.Possibly the problem you are experiencing with
ContentManager.Loadis because you are including the file extension in your file name. It adds the.xnbfor you, and will get confused if you add it as well.