Change texture of object created in game

Ok so I am making a card game and I am having a bit of difficulty applying the textures to cards. Now doing this in the inspect is no problem, just add a sprite renderer and drag and done. However this won’t work for me as the cards are created as they are drawn from the deck and added to the player or enemy hand.

So each card has a string variable called front which contains the texture name. I am able to create the cards as new objects fine but I am not sure how to apply the texture to each of them in my script.

Essentially what I want to do is take the value from the card’s data which contains the asset name and then load it onto that object. I’m not really sure how to do this in code and I’ve made a few attempts and none have worked so far.

	void AddToPlayerHand()
	{
		CardDef c1 = playerDeck.Deal();
		if(c1 != null)
		{
			GameObject newObj = new GameObject();
			newObj.name = "Card";
			CardAttributes newCard = newObj.AddComponent(typeof(CardAttributes))as CardAttributes;
			BoxCollider bc = newObj.AddComponent(typeof(BoxCollider)) as BoxCollider;
			Renderer ren = newObj.AddComponent(typeof(Renderer)) as Renderer;
			newCard.Data = c1;
			newObj.transform.parent = playerDeck.transform;
			float x = -6+(playerDeck.deck.Count)*1.0f;
			float y = -6;
			Texture cardTexture;//= newCard.Data.Front;
			cardTexture = Resources.Load("cardfront",typeof(Texture)) as Texture;
			Vector2 pos = new Vector2(x,y);
			newObj.transform.position = pos;
			newObj.renderer.material.mainTexture = cardTexture;
			playerHand.Add(c1);

		}

	}

Renderer (by the way you should not add Renderer component, but a derived component like MeshRenderer for example, this one needs also a MeshFilter that has a valid mesh set) has no material by default, you must create it earlier in code (or easier, create one empty in editor and assign it to a variable in your script), assign the material to the renderer and finally apply your line 19.

Also to have a better code you don’t need the explicit cast when you use AddComponent (or GetComponent/GetComponents), since you’re using C#:

CardAttributes newCard = newObj.AddComponent<CardAttributes>();
// ...same for all the others AddComponent

It’s just much more human-readable, isn’t it? :slight_smile: