1
\$\begingroup\$

Dear Stackoferflow Fourm I would like to have a function in my Android Game Programming that allows the user to choose his own background image (I would like to let the user change the plane image) Unfortunately I have no idea how I could do that. If someone knows how to do it I would be very happy.!

Sceneview

Game view

New contributor
Lomusire is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
\$\endgroup\$
  • 1
    \$\begingroup\$ Where is the new texture supposed to come from? Do you have a set of textures to choose from build into the game? Local filesystem? Internet URL? \$\endgroup\$ – Philipp Nov 22 at 10:57
  • \$\begingroup\$ I want the user to upload his picture from the local filesystem. \$\endgroup\$ – Lomusire Nov 22 at 11:10
1
\$\begingroup\$

At it's most fundamental, you need to load an image into a texture and then apply that texture to a material. You can do that as follows:

 public void SetImage(string filePath) {
     // Create a variable to hold the texture
     Texture2D tex = null;
     byte[] fileData;
 
     // Check file exists
     if (File.Exists(filePath)) {
         // Read contents into a byte array
         fileData = File.ReadAllBytes(filePath);

         // Create a new texture and load the image data
         tex = new Texture2D(2, 2);
         tex.LoadImage(fileData);
     } else {
         Debug.LogWarningFormat("{0} not found", filePath);
     }
     // Set the main texture for the material on the current object's renderer
     this.GetComponent<Renderer>().material.mainTexture = tex;
 }

The more interesting part comes when you want to do this with a user-selected file.

First of all, you need to work out which platforms you want to support. A file browse dialog on Windows is radically different to one on Android.

Next, you need to decide how long this will persist. If it's just until the game closes, you're fine.

If, on the other hand, you want to persist across game restarts then you need to do one or two things:

  • Pick/develop a mechanism to allow you to remember which file (the|each) user chose.
  • Optionally make a "safe" copy of the image somewhere in your application's data directory, so that if the original is deleted, you can continue to show it in-game. [again, this will depend significantly on which platforms you support]
| improve this answer | |
\$\endgroup\$

Your Answer

Lomusire is a new contributor. Be nice, and check out our Code of Conduct.

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.