Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load material from assets in Unity

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

like image 418
Tarik Mokafih Avatar asked Jan 21 '15 11:01

Tarik Mokafih


People also ask

How do I load materials in Unity?

Use the FBX Importer's Materials tab to import Materials from your imported Assets. When you first open the Materials tab, it looks like this: Tick Import Materials to open the settings for importing Materials from your imported Assets. Choose this option to extract imported Materials as external Assets.

How do I load an asset in Unity?

Click the Go to My Assets button to view the assets you have already chosen. Another way to import assets into your Unity Project is for you to open your Project in the Unity Engine and click Import New Asset or go to Assets > Import Package > Custom Package, and locate your asset on your computer.

How do I reference Assets in Unity?

An "asset" in Unity is file in the Project window such as an AnimationClip , Texture , Prefab, or any script which inherits from ScriptableObject . Very easy to use. Just add a serialized field to your script then drag and drop the asset you want into that field in the Inspector.


1 Answers

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 unity5 syntax

myMaterial = Resources.Load("Materials/Night_Sky"); 
like image 119
MX D Avatar answered Oct 16 '22 04:10

MX D