Search code examples
c#functionxna-4.0texture2d

Send Texture2d object to function


I try to send some object to a function but seems C# doesn't like that. This is the code.

string[] bkgrSource = new string[12];
Texture2D[] bkgrBANK = new Texture2D[12];

which bkgrSource[0] is an array of filenames and bkgrBANK[0] is an array of Texture2D.

This function is not working. The bkgrBANK[0] will remains empty. Any help?

commonImageLoader( bkgrSource[0], bkgrBANK[0] ); 

private void commonImageLoader(string source, Texture2D destination ) {
    if ( !string.IsNullOrEmpty( source ) ) {
        fileName = source;
        using ( fileStream = new FileStream( @fileName, FileMode.Open ) ) {
        destination = Texture2D.FromStream( GraphicsDevice, fileStream );
        }
    }
}

Solution

  • I'm not a C# guru, but I think the point is that you are passing parameter by value (default method call behavior), So source and destination parameters in your function are a copy of the original ones.

    I think you can pass parameter by reference to solve this issue. Probably this should work:

    commonImageLoader( ref bkgrSource[0], ref bkgrBANK[0] ); 
    
    private void commonImageLoader(ref string source, ref Texture2D destination ) {
        if ( !string.IsNullOrEmpty( source ) ) {
            fileName = source;
            using ( fileStream = new FileStream( @fileName, FileMode.Open ) ) {
            destination = Texture2D.FromStream( GraphicsDevice, fileStream );
            }
        }
    }