I read the docs and this should work
MeshRenderer mesh_renderer = gameObject.GetComponent<MeshRenderer> ();
mesh_renderer.material = Resources.Load<Material> ("MapMaterial");
mesh_renderer.material.mainTexture = Resources.Load<Texture> ("cobblestone");
But it assigns an empty default material.
cobblestone.jpg is in the assets folder so it should work right?
No it will search for the resource you're asking relative to the Assets\Resources folder.
// This will search for 'cobblestone' in Assets/Resources/cobblestone.jpg:
mesh_renderer.material.mainTexture = Resources.Load("cobblestone", typeof(Texture2D));
Related
I have am developing a HoloLens project that needs to reference .txt files. I have the files stored in Unity's 'Resources' folder and have them working perfectly fine (when run via Unity):
string basePath = Application.dataPath;
string metadataPath = String.Format(#"\Resources\...\metadata.txt", list);
// If metadata exists, set title and introduction strings.
if (File.Exists(basePath + metadataPath))
{
using (StreamReader sr = new StreamReader(new FileStream(basePath + metadataPath, FileMode.Open)))
{
...
}
}
However, when building the program for HoloLens deployment, I am able to run the code but it doesn't work. None of the resources show up and when examining the HoloLens Visual Studio solution (created by selecting build in Unity), I don't even see a resources or assets folder. I am wondering if I am doing something wrong or if there was a special way to deal with such resources.
Also with image and sound files...
foreach (string str in im)
{
spriteList.Add(Resources.Load<Sprite>(str));
}
The string 'str' is valid; it works absolutely fine with Unity. However, again, it's not loading anything when running through the HoloLens.
You can't read the Resources directory with the StreamReader or the File class. You must use Resources.Load.
1.The path is relative to any Resources folder inside the Assets folder of your project.
2.Do not include the file extension names such as .txt, .png, .mp3 in the path parameter.
3.Use forward slashes instead of back slashes when you have another folder inside the Resources folder. backslashes won't work.
Text files:
TextAsset txtAsset = (TextAsset)Resources.Load("textfile", typeof(TextAsset));
string tileFile = txtAsset.text;
Supported TextAsset formats:
txt .html .htm .xml .bytes .json .csv .yaml .fnt
Sound files:
AudioClip audio = Resources.Load("soundFile", typeof(AudioClip)) as AudioClip;
Image files:
Texture2D texture = Resources.Load("textureFile", typeof(Texture2D)) as Texture2D;
Sprites - Single:
Image with Texture Type set to Sprite (2D and UI) and
Image with Sprite Mode set to Single.
Sprite sprite = Resources.Load("spriteFile", typeof(Sprite)) as Sprite;
Sprites - Multiple:
Image with Texture Type set to Sprite (2D and UI) and
Image with Sprite Mode set to Multiple.
Sprite[] sprite = Resources.LoadAll<Sprite>("spriteFile") as Sprite[];
Video files (Unity >= 5.6):
VideoClip video = Resources.Load("videoFile", typeof(VideoClip)) as VideoClip;
GameObject Prefab:
GameObject prefab = Resources.Load("shipPrefab", typeof(GameObject)) as GameObject;
3D Mesh (such as FBX files)
Mesh model = Resources.Load("yourModelFileName", typeof(Mesh)) as Mesh;
3D Mesh (from GameObject Prefab)
MeshFilter modelFromGameObject = Resources.Load("yourGameObject", typeof(MeshFilter)) as MeshFilter;
Mesh loadedMesh = modelFromGameObject.sharedMesh; //Or design.mesh
3D Model (as GameObject)
GameObject loadedObj = Resources.Load("yourGameObject") as GameObject;
//MeshFilter meshFilter = loadedObj.GetComponent<MeshFilter>();
//Mesh loadedMesh = meshFilter.sharedMesh;
GameObject object1 = Instantiate(loadedObj) as GameObject;
Accessing files in a sub-folder:
For example, if you have a shoot.mp3 file which is in a sub-folder called "Sound" that is placed in the Resources folder, you use the forward slash:
AudioClip audio = Resources.Load("Sound/shoot", typeof(AudioClip)) as AudioClip;
Asynchronous Loading:
IEnumerator loadFromResourcesFolder()
{
//Request data to be loaded
ResourceRequest loadAsync = Resources.LoadAsync("shipPrefab", typeof(GameObject));
//Wait till we are done loading
while (!loadAsync.isDone)
{
Debug.Log("Load Progress: " + loadAsync.progress);
yield return null;
}
//Get the loaded data
GameObject prefab = loadAsync.asset as GameObject;
}
To use: StartCoroutine(loadFromResourcesFolder());
If you want to load text file from resource please do not specify file extension
just simply follow the below given code
private void Start()
{
TextAsset t = Resources.Load<TextAsset>("textFileName");
List<string> lines = new List<string>(t.text.Split('\n'));
foreach (string line in lines)
{
Debug.Log(line);
}
}
debug.Log can print all the data that are available in text file
You can try to store your text files in streamingsasset folder. It works fine in my project
I am trying to create particles emission for my objects which are actually pawns in a chess game. I changed particles material using Inspector for particle system and it works fine, however, when I try to change it with a script, nothing happens (particles stay pink for the black pawn).
I am not sure what is wrong with the script, whether it's a change of material problem or maybe I need to set the path for material. I would be glad if someone suggested a solution!
Here is the script:
public class BlackPawnParticleSystem : MonoBehaviour
{
private Material m_Material;
private ParticleSystemRenderer psr;
private void Start()
{
var ps = GetComponent<ParticleSystem>();
m_Material = GetComponent<Renderer>).material;
psr = GetComponent<ParticleSystemRenderer>);
psr.material = Resources.GetBuiltinResource<Material>("BlackBishop.mat");
}
This is how it looks like:
EDIT:
Changes in code:
public class BlackPawnParticleSystem : MonoBehaviour
{
private Material m_Material;
private ParticleSystemRenderer psr;
private void Start()
{
var ps = GetComponent<ParticleSystem>();
m_Material = GetComponent<Renderer>().material;
psr = GetComponent<ParticleSystemRenderer>();
psr.material = Resources.Load<Material>("BlackBishop");
}
Location of my materials:
Inspector for the material:
Script attached to the object:
The problem is this line: Resources.GetBuiltinResource<Material>("BlackBishop.mat")
It is returning null. The Resources.GetBuiltinResource function is used to load resources that are built-in into Unity not ones created by you. For example, "Sprites-Default.mat". There is no build-in material named "BlackBishop.mat" so it returns null.
To load material you created, use rhe Resources.Load function.
First, create a folder called "Resources" then put your "BlackBishop.mat" material there. You can now load it as below:
Resources.Load<Material>("BlackBishop");
Notice how I did not include ".mat" in the name. You don't include the extension name when using the Resources.Load function. If you do, it will not find it.
EDIT:
But still nothing happens on my game scene
Please carefully:
1.Like I said in my original answer, you must create a folder named "Resources" and must put the "Black Bishop" material inside that folder. You have not done this and it should not work. The spellings of thisfolder must be correct so copy it directly from this answer. Again, it should be named "Resources".
2.Your material is named "Black Bishop" not "BlackBishop" . See the space. Please fix this in the code. That should be Resources.Load<Material>("Black Bishop"); not Resources.Load<Material>("BlackBishop");.
3.Your material is currently using the "Standard" shader. Change that to Particle shader. You can do that by selecting the Material and changing the shader from "Standard" to "Particles/Alpha Blended Premultiply". That's it. Your problem should now be solved.
Extra:
I noticed you are using folders to organize your resources. Your "Black Bishop.mat" is inside Arcane Cyber --> Chess --> Materials --> Pieces --> Plastic. I suggest you move the "Materials" folder to the "Resources" folder created in #1 above.
Now, your "Black Bishop.mat" should be inside Assets --> Resources --> Materials --> Pieces --> Plastic.
You can now load it as:
Resources.Load<Material>("Materials/Pieces/Plastic/Black Bishop");
If you still have problems, please update your code and new Inspector images again. Remember that spellings count.
Why not just make a SerializedField with the Materials you need? If you don't want materials and trails to be random, set them to the exact spot in the array you need for the situation.
I did it like this:
using UnityEngine;
public class CorrectParticles : MonoBehaviour
{
private static ParticleSystem correctPart;
private static ParticleSystemRenderer correctRend;
public static CorrectParticles Instace;
[SerializeField] Material[] mainMaterials;
[SerializeField] Material[] trailMaterials;
private void Awake()
{
Instace = this;
}
void Start()
{
correctPart = GetComponent<ParticleSystem>();
correctRend = GetComponent<ParticleSystemRenderer>();
correctPart.Stop();
}
public void StartParticles()
{
int mainMaterial = Random.Range(0, mainMaterials.Length);
correctRend.material = mainMaterials[mainMaterial];
int trailMaterial = Random.Range(0, trailMaterials.Length);
correctRend.trailMaterial = trailMaterials[trailMaterial];
correctPart.Play();
}
public void StopParticles()
{
correctPart.Stop(withChildren: true, stopBehavior: ParticleSystemStopBehavior.StopEmittingAndClear);
}
}
Then I can start and stop the particle system as needed on other scripts.
CorrectParticles.Instace.StartParticles();
or
CorrectParticles.Instace.StopParticles();
I have am developing a HoloLens project that needs to reference .txt files. I have the files stored in Unity's 'Resources' folder and have them working perfectly fine (when run via Unity):
string basePath = Application.dataPath;
string metadataPath = String.Format(#"\Resources\...\metadata.txt", list);
// If metadata exists, set title and introduction strings.
if (File.Exists(basePath + metadataPath))
{
using (StreamReader sr = new StreamReader(new FileStream(basePath + metadataPath, FileMode.Open)))
{
...
}
}
However, when building the program for HoloLens deployment, I am able to run the code but it doesn't work. None of the resources show up and when examining the HoloLens Visual Studio solution (created by selecting build in Unity), I don't even see a resources or assets folder. I am wondering if I am doing something wrong or if there was a special way to deal with such resources.
Also with image and sound files...
foreach (string str in im)
{
spriteList.Add(Resources.Load<Sprite>(str));
}
The string 'str' is valid; it works absolutely fine with Unity. However, again, it's not loading anything when running through the HoloLens.
You can't read the Resources directory with the StreamReader or the File class. You must use Resources.Load.
1.The path is relative to any Resources folder inside the Assets folder of your project.
2.Do not include the file extension names such as .txt, .png, .mp3 in the path parameter.
3.Use forward slashes instead of back slashes when you have another folder inside the Resources folder. backslashes won't work.
Text files:
TextAsset txtAsset = (TextAsset)Resources.Load("textfile", typeof(TextAsset));
string tileFile = txtAsset.text;
Supported TextAsset formats:
txt .html .htm .xml .bytes .json .csv .yaml .fnt
Sound files:
AudioClip audio = Resources.Load("soundFile", typeof(AudioClip)) as AudioClip;
Image files:
Texture2D texture = Resources.Load("textureFile", typeof(Texture2D)) as Texture2D;
Sprites - Single:
Image with Texture Type set to Sprite (2D and UI) and
Image with Sprite Mode set to Single.
Sprite sprite = Resources.Load("spriteFile", typeof(Sprite)) as Sprite;
Sprites - Multiple:
Image with Texture Type set to Sprite (2D and UI) and
Image with Sprite Mode set to Multiple.
Sprite[] sprite = Resources.LoadAll<Sprite>("spriteFile") as Sprite[];
Video files (Unity >= 5.6):
VideoClip video = Resources.Load("videoFile", typeof(VideoClip)) as VideoClip;
GameObject Prefab:
GameObject prefab = Resources.Load("shipPrefab", typeof(GameObject)) as GameObject;
3D Mesh (such as FBX files)
Mesh model = Resources.Load("yourModelFileName", typeof(Mesh)) as Mesh;
3D Mesh (from GameObject Prefab)
MeshFilter modelFromGameObject = Resources.Load("yourGameObject", typeof(MeshFilter)) as MeshFilter;
Mesh loadedMesh = modelFromGameObject.sharedMesh; //Or design.mesh
3D Model (as GameObject)
GameObject loadedObj = Resources.Load("yourGameObject") as GameObject;
//MeshFilter meshFilter = loadedObj.GetComponent<MeshFilter>();
//Mesh loadedMesh = meshFilter.sharedMesh;
GameObject object1 = Instantiate(loadedObj) as GameObject;
Accessing files in a sub-folder:
For example, if you have a shoot.mp3 file which is in a sub-folder called "Sound" that is placed in the Resources folder, you use the forward slash:
AudioClip audio = Resources.Load("Sound/shoot", typeof(AudioClip)) as AudioClip;
Asynchronous Loading:
IEnumerator loadFromResourcesFolder()
{
//Request data to be loaded
ResourceRequest loadAsync = Resources.LoadAsync("shipPrefab", typeof(GameObject));
//Wait till we are done loading
while (!loadAsync.isDone)
{
Debug.Log("Load Progress: " + loadAsync.progress);
yield return null;
}
//Get the loaded data
GameObject prefab = loadAsync.asset as GameObject;
}
To use: StartCoroutine(loadFromResourcesFolder());
If you want to load text file from resource please do not specify file extension
just simply follow the below given code
private void Start()
{
TextAsset t = Resources.Load<TextAsset>("textFileName");
List<string> lines = new List<string>(t.text.Split('\n'));
foreach (string line in lines)
{
Debug.Log(line);
}
}
debug.Log can print all the data that are available in text file
You can try to store your text files in streamingsasset folder. It works fine in my project
I have am developing a HoloLens project that needs to reference .txt files. I have the files stored in Unity's 'Resources' folder and have them working perfectly fine (when run via Unity):
string basePath = Application.dataPath;
string metadataPath = String.Format(#"\Resources\...\metadata.txt", list);
// If metadata exists, set title and introduction strings.
if (File.Exists(basePath + metadataPath))
{
using (StreamReader sr = new StreamReader(new FileStream(basePath + metadataPath, FileMode.Open)))
{
...
}
}
However, when building the program for HoloLens deployment, I am able to run the code but it doesn't work. None of the resources show up and when examining the HoloLens Visual Studio solution (created by selecting build in Unity), I don't even see a resources or assets folder. I am wondering if I am doing something wrong or if there was a special way to deal with such resources.
Also with image and sound files...
foreach (string str in im)
{
spriteList.Add(Resources.Load<Sprite>(str));
}
The string 'str' is valid; it works absolutely fine with Unity. However, again, it's not loading anything when running through the HoloLens.
You can't read the Resources directory with the StreamReader or the File class. You must use Resources.Load.
1.The path is relative to any Resources folder inside the Assets folder of your project.
2.Do not include the file extension names such as .txt, .png, .mp3 in the path parameter.
3.Use forward slashes instead of back slashes when you have another folder inside the Resources folder. backslashes won't work.
Text files:
TextAsset txtAsset = (TextAsset)Resources.Load("textfile", typeof(TextAsset));
string tileFile = txtAsset.text;
Supported TextAsset formats:
txt .html .htm .xml .bytes .json .csv .yaml .fnt
Sound files:
AudioClip audio = Resources.Load("soundFile", typeof(AudioClip)) as AudioClip;
Image files:
Texture2D texture = Resources.Load("textureFile", typeof(Texture2D)) as Texture2D;
Sprites - Single:
Image with Texture Type set to Sprite (2D and UI) and
Image with Sprite Mode set to Single.
Sprite sprite = Resources.Load("spriteFile", typeof(Sprite)) as Sprite;
Sprites - Multiple:
Image with Texture Type set to Sprite (2D and UI) and
Image with Sprite Mode set to Multiple.
Sprite[] sprite = Resources.LoadAll<Sprite>("spriteFile") as Sprite[];
Video files (Unity >= 5.6):
VideoClip video = Resources.Load("videoFile", typeof(VideoClip)) as VideoClip;
GameObject Prefab:
GameObject prefab = Resources.Load("shipPrefab", typeof(GameObject)) as GameObject;
3D Mesh (such as FBX files)
Mesh model = Resources.Load("yourModelFileName", typeof(Mesh)) as Mesh;
3D Mesh (from GameObject Prefab)
MeshFilter modelFromGameObject = Resources.Load("yourGameObject", typeof(MeshFilter)) as MeshFilter;
Mesh loadedMesh = modelFromGameObject.sharedMesh; //Or design.mesh
3D Model (as GameObject)
GameObject loadedObj = Resources.Load("yourGameObject") as GameObject;
//MeshFilter meshFilter = loadedObj.GetComponent<MeshFilter>();
//Mesh loadedMesh = meshFilter.sharedMesh;
GameObject object1 = Instantiate(loadedObj) as GameObject;
Accessing files in a sub-folder:
For example, if you have a shoot.mp3 file which is in a sub-folder called "Sound" that is placed in the Resources folder, you use the forward slash:
AudioClip audio = Resources.Load("Sound/shoot", typeof(AudioClip)) as AudioClip;
Asynchronous Loading:
IEnumerator loadFromResourcesFolder()
{
//Request data to be loaded
ResourceRequest loadAsync = Resources.LoadAsync("shipPrefab", typeof(GameObject));
//Wait till we are done loading
while (!loadAsync.isDone)
{
Debug.Log("Load Progress: " + loadAsync.progress);
yield return null;
}
//Get the loaded data
GameObject prefab = loadAsync.asset as GameObject;
}
To use: StartCoroutine(loadFromResourcesFolder());
If you want to load text file from resource please do not specify file extension
just simply follow the below given code
private void Start()
{
TextAsset t = Resources.Load<TextAsset>("textFileName");
List<string> lines = new List<string>(t.text.Split('\n'));
foreach (string line in lines)
{
Debug.Log(line);
}
}
debug.Log can print all the data that are available in text file
You can try to store your text files in streamingsasset folder. It works fine in my project
I'm working on an augmented Reality project in Unity where the user will be able to see an animated sprite on their phone when pointing the camera at a certain image.
The Sprite will be created by a belgian comic book artist and will be quite lengthy. To make my life easier I wanted to create an editor script that takes all the sprites from the Resources/Sprite folder and creates an AnimationClip.
Sprite[] sprites = Resources.LoadAll<Sprite>("sprite");
AnimationClip animClip = new AnimationClip();
animClip.frameRate = 25; // fps
EditorCurveBinding spriteBinding = new EditorCurveBinding();
spriteBinding.type = typeof(SpriteRenderer);
spriteBinding.path = "";
spriteBinding.propertyName = "m_Sprite";
ObjectReferenceKeyframe[] spriteKeyFrames = new ObjectReferenceKeyframe[sprites.Length];
for (int i = 0; i < (sprites.Length); i++)
{
spriteKeyFrames[i] = new ObjectReferenceKeyframe();
spriteKeyFrames[i].time = i / animClip.frameRate;
spriteKeyFrames[i].value = sprites[i];
}
AnimationUtility.SetObjectReferenceCurve(animClip, spriteBinding, spriteKeyFrames);
AnimationClipSettings animClipSett = new AnimationClipSettings();
animClipSett.loopTime = true;
AnimationUtility.SetAnimationClipSettings(animClip, animClipSett);
AssetDatabase.CreateAsset(animClip, "assets/generated.anim");
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
This works, an AnimationClip is created but when using it in the Animation Panel nothing happens.
I made the same Animation manually to see if that would work and it does.
The blue bar in the animation panel moves though
Animator Panel showing the generated AnimationClip:
The only noticable difference I've found (besides one of them playing and the other one doesn't) is that the generated clip's Length changes to 0 after trying to run it's animation
The Sprite Object and inspector:
I'be been trying to find what I'm doing wrong for half a day now without getting a single step closer.
I'd like to thank who answers on this question in advance.
Greetings,
Maethorian