Load material from assets in Unity

15,173

This will not work as Resources.Load requires you to place the object in the Resources folder. This information can also be found in the Unity Docs

For this to properly work you will need to create a folder called Resources Inside the Assets folder. After which you can add the Material folder to this. So the folder structure would look as following

Assets/Resources/Materials/Night_Sky.mat

Further more the script to load the material looks just fine.

If you really do not wish to use the resources folder, you can try to obtain the materials using System.IO folder search options instead. But I would advice you to just use the build in Resources function.

When you do use the Resources.Load() however, you will need to keep a few things in mind. The path is case-sensitive and requires you to add the file extension as well. So in the example above, that would result in:

myMaterial = Resources.Load("Materials/Night_Sky.mat"); 

Unity 5.0 or >

As Nika Kasradze mentioned in the comments. In unity 5.0 or up extensions must be omitted. Making the correct syntax

myMaterial = Resources.Load("Materials/Night_Sky"); 
Share:
15,173

Related videos on Youtube

Tarik Mokafih
Author by

Tarik Mokafih

Updated on June 04, 2022

Comments

  • Tarik Mokafih
    Tarik Mokafih almost 2 years

    In my Assets folder I have a folder named Material where I stored all the needed materials, One of the materials in the Material folder is Night_Sky, which I want at a certain moment of the game to replace the day_sky and set Night_sky as my default Skybox. I tried many codes all of them return null object, examples :

    night = Resources.Load("Material", typeof(Material)) as Material;
    

    or

    night = Resources.Load("Material/Night_Sky.mat", typeof(Material)) as Material;
    

    How can I load my Night_Sky material, or if there is an easier way to switch my skybox to night_sky thank you for sharing it

  • Alex Cio
    Alex Cio over 8 years
    This doesn't work for me. I tried different things, but loading the Material never works. Tried also different directories as well as with and without suffix but the Material always stays null. Setting the material inside a public variable inside the inspector is no problem. But I really would like to know how to load it programmatically.
  • MX D
    MX D over 8 years
    @亚历山大 if it is not working make sure of the following things case sensitivity the path is case sensitive. casting to type As material or typeof(material) are required. file extension is also required to be added. And to load it you have to cast the path from Resources, so in the example above it would result in myMaterial = Resources.Load("Materials/Night_Sky.mat"); You can also take a look at the answer given on this post
  • Sachin
    Sachin over 7 years
    I can get Material with the help of last comment myMaterial = Resources.Load("Materials/Night_Sky.mat"); Thanks a lot..