How can I change GameObject's texture?

I want to change GameObjects texture when I press Space. Atm I have something like this:

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

    public Texture texture;
	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
        if (Input.GetKeyDown(KeyCode.Space)){
            Debug.Log("itsworking",gameObject);
            gameObject.GetComponent<Renderer>().material.mainTexture = texture;
        }
	}
}

And I have dragged the texture to that little box that appears when you make a variable public.
Oh and when I do press space it showes me a preview at the right down corner of the image that I want it to change. Also I have another texture in the SpriteRenderer component.

Renderer and SpriteRenderer are not the same thing, there’s a difference.

 using UnityEngine;
 using System.Collections;
 
 public class PlayerController : MonoBehaviour {
 
     public Sprite sprite;
     
     // Update is called once per frame
     void Update () {
         if (Input.GetKeyDown(KeyCode.Space)){
             Debug.Log("itsworking",gameObject);
             gameObject.GetComponent<SpriteRenderer>().sprite = sprite;
         }
     }
 }

Scripting API - Renderer

Scripting API - SpriteRenderer

Manual - SpriteRenderer