Problem loading Materials from Resources

In the game I’m making, I have some objects which I want to change the material. I have a .txt file with the list of materials and I read it into a TextAsset. Then I put each line of the TextAsset into a string[ ] using Split(‘’\n’). Finally, I do a Resources.Load(material, typeof(Material)) as Material and assign it to the object’s renderer.material.

When I do this:

string newmat = "Materials/Spheres/" + spheresTextures[int.Parse(spheresNumbers[i])];
Debug.Log(newmat);
sphereObject[i].renderer.material = Resources.Load (newmat, typeof(Material)) as Material;

I get

Materials/Spheres/dark-green-001 on the Console, but the spheres have None material assigned.

On the other hand, if I do it manually, like:

string newmat = "Materials/Spheres/dark-green-001";
sphereObject[i].renderer.material = Resources.Load (newmat, typeof(Material)) as Material;

then it works.

For the life of me, I cannot understand why the same text I copied from the console works, when hardcoding the variable newmat, but it doesn’t work when assigning the variable from the string[ ].

Anybody experiencing the same?

Thanks for any help.

Found the problem :smile:

spheresTextures contained the list of textures, but it contained the extension .jpg too for each texture. Removing the .jpg from each one, has solved the problem.

I also got a similar issue, but cannot solve, my game objects got al pink if I try to assign a material programatically. Don’t know how it works, because seems everyone got it work without issues.

My project structure its

Assets/
    Resources/
        Dirt.mat
    Voxel/
        Chunk.cs <-- Here I'm trying to load the material (dunno if the folder structure affects it)
using UnityEngine;
using System.Collections;

public class Chunk : MonoBehaviour {

	// Use this for initialization
	void Start () {
		Material material = (Material)Resources.Load ("Resources/Dirt", typeof(Material)); // Also try with "Dirt" only and "Assets/Resources/Dirt"
		// This function always return null in the standalone player or web player. This is useful for quickly accessing an asset for use in the editor only. <-- This one I've take from the documentation but don't work even when build and run
		if(material == null) material = (Material)Resources.LoadAssetAtPath<Material> ("Resources/Dirt");

		Debug.Log (material); // <-- Return null
	}
	
	// Update is called once per frame
	void Update () {
	
	}
}