How I do something like eval() but not eval() ?

Hello,

I’m working on a project where I want to dynamically load textures into Unity at runtime and apply them to buttons. It’s pulling all of the texture names out of the Resources directory just fine, and I have all of the arrays the texture names without extensions. I have even built the commands so that print() them and cut and paste the generated code into the program it works fine. So when I try and execute the variable that contains the entire command I want to execute, nothing happens. It doesn’t create the Textures, and certainly doesn’t assign them.

Now the only way I know of executing a variable as a command in Unity is eval(). I know that it is a command that is best left alone, but I don’t know anything that is better. Anyone have any ideas?

Best,

Steve

for(var p:int = 0;p < textureNameArray.length; p++)
{
	for( var q:int = 0; q < textureArray.GetUpperBound(0); q++)
	{
		if(textureNameArray[p] == textureArray[q,0])
		{
			command = ("var " + textureArray[q,0] + "Texture" + q + ":Texture = Resources.Load(\"" + textureArray[q,1] + "\", Texture) ;");
			print(command);
			eval(command);
		}
	}
}

// This is a sample of the code that is output as a result.
var hexesTexture26:Texture = Resources.Load("hexes_tape_1_icon", Texture) ;

Adding some upadated code.

for(var p:int = 0;p < textureNameArray.length; p++)
{
	for( var q:int = 0; q < textureArray.GetUpperBound(0); q++)
	{
		if(textureNameArray[p] == textureArray[q,0])
		{
			textureName = textureArray[q,0] + "Texture" + q;
			print("textureName " + textureName);
			textureFileName = "\"" + textureArray[q,1] + "\"";
			print("textureFileName " + textureFileName);
			MakeTexture(textureName,textureFileName);
		}
	}
}

function MakeTexture(makeTextureNameID,makeTextureFileNameID)
{
	print("makeTextureNameID " + makeTextureNameID);
	print("makeTextureFileNameID " + makeTextureFileNameID);
	var makeTextureNameID : Texture = Resources.Load(makeTextureFileNameID,Texture);
}

I understand your intentions, its just how you’re going about it is a bit off. :wink:

It sounds like you really need to be storing all your textures in a multidimensional array. It looks like you start to do that with textureArray but then you leave that behind and start trying to generate code on the fly. To actually do what you want, you need reflection, but that’s cumbersome and really isn’t needed here. I’m not sure why you can’t do something like:

var textures = new Texture[ x , y ];

function FillTextureArray () {
     for( var i = 0 ; i < x ; i++) {
          for( var j = 0 ; j < y ; j++) {
               textures[ i , j ] = Resources.Load( "Texture" + i.ToString() + j.ToString() , Texture);
               // in textures[1,2] goes "texture12" or whatever similar naming scheme you have.
          }
     }
}

As long as I understand what you’re doing this sounds easier and faster.