Not sure how to change mesh materials in code

I’ve tried several different ways of coding this and looking at answers online, and I’m just hopelessly confused at this point, so I’ll just describe what I’m doing without code and how I’m trying to code this.

When adding a texture to a mesh I’m currently dragging a sprite into my Resources/Sprites folder in unity and then dragging it onto the mesh prefab, which seems to automatically make a material out of said texture. I’m trying to do this process with code: I drag a sprite into unity, I manually create a material in the Resources/Sprites/Materials and drag the sprite onto that. Then in my mesh script I do

Texture mat1 = Resources.Load<Texture("Sprites/Materials/tilesheet1");

gameObject.renderer.material.mainTexture = mat1;

Unfortunately this doesn’t work, and I’ve tried many other attempts with some errors like “InvalidCastException: Cannot cast from source type to destination type”, and I’m not even sure I’m doing this right. Am I supposed to change the texture or the material? The code I’ve been looking at when skimming answers seems to suggest casting the material as a texture and using that, but I am pretty confused about this whole process.

Edit: Okay, setting it to the texture the material is based on does work, but I’m a little confused as to how to set the material information like the shader and whatnot if I don’t use the actual material.

I think you have some confusion what is what.

If you want to set texture you do this:

Texture tex1 = Resources.Load<Texture>("Sprites/myTexture"); // i.e. .png, .jpg, etc
gameObject.renderer.material.mainTexture = tex1;

If you want to set material you do this:

Material mat1 = Resources.Load<Material>("Sprites/myMaterial"); // i.e. .mat files
gameObject.renderer.material = mat1;