Changing the Material / Texture of an existing gameObject

Hi there,

I currently started to create a 2D round-based strategy game with unity. I got a plane as grid having more smaller planes on it representing a grid, on which you can place buildings like for example "barracks". Now simply to have test version I tried to get the selected plane with 'RayCast' and 'RayCastHit'. What I want is to "build" something on this empty plane, so I want to draw a building onto this plane. I have the existing "Material" / Texture in my assets, but I can not load it onto my plane.

You can assign a material to a mesh renderer programmatically. The GameObject class has a 'renderer' field that will be non-null if a renderer is attached (in C#, the Monobehaviour class has a 'renderer' field as well that can be used as a shortcut - not sure how it works in UnityScript). The Renderer class has a material field, so to assign a new material to a game object, you would write something like this:

renderer.material = newMaterial;

Or, if manipulating the object externally (e.g. using the result of a raycast):

targetObject.renderer.material = newMaterial;

I know this answer is 5 years late, but maybe someone would see it when they search for the same question.

private SpriteRenderer MySpriteRenderer; //Declare a global variable
public Sprite sprite1; //the sprites you want to use
public Sprite sprite2;
public Sprite sprite3;

void Start()
{
//some code
MySpriteRenderer = GetComponent ();
if (MySpriteRenderer.sprite == null)
MySpriteRenderer.sprite = sprite1;
//some code
}

//in the method that changes the sprite, use a line like this:
MySpriteRenderer.sprite = sprite1;