Wednesday, 30 November 2016

Changing textures at runtime in Unity

One of the things we're keen to get working for our Unity game is the ability to customise Fantasy Football characters. As different characters have different amounts of armour, we're modelling the characters with every possible armour piece attached, and then disable them at runtime in Unity.

To be able to do that would be pretty cool.
What would be super-cool would be to have the player design their own team strip (perhaps using some kind of web editor) and then have their players clad in their own custom colours.

To do that would require generating and changing textures on-the-fly. Now we're pretty sure - with some PHP and GDI+ - we can generate the appropriate png at runtime. What we need is a routine to allow us to change the texture of an object at runtime in Unity.

Luckily, it's not that difficult:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class loadTexture : MonoBehaviour {

   public GameObject target;
   public string web;

   // Use this for initialization
   void Start () {
      if (web.Length > 0) {
         StartCoroutine (loadImage (target, web));
      }
   }

   private IEnumerator loadImage( GameObject page, string url ) {
      WWW www = new WWW( url );
      yield return www;
      page.GetComponent<Renderer>().material.mainTexture = www.texture;
   }


}

We set the script up by dragging the orc skin into the "target" field, and setting the URL to our (local) web server.


When the game engine runs, our orc appears with the default green skin:


But when the next texture has finished downloading, the skin colour changes immediately.


It's only a little thing, but it's pretty exciting for our game idea; we've potentially got the ability to allow players to create (and download) their own team colours - and in Unity it simply means loading a new (single) texture/png from the web server.

When playing against an opponent, the Unity app could download their team colours, thus allowing both players to completely customise their own teams - and have their team colours appear in other people's games.

The original (or, more accurately, the second edition) Blood Bowl boardgame came with a number of "endzone" markers, for different teams. The game was very much about customising the teams - creating your own team name, mascot, insignia, team colours etc. In the game, the endzones at the end of the playing surface were simple double-sided strips of card which could be swapped out depending on which team(s) were playing.



Not only could we provide players with the ability to create their own team colours, we could even have custom in-game end-zones by simply swapping out a texture or two.

Now that would be pretty cool.....


No comments:

Post a Comment