I want to change AudioSources volume and I want to achieve it by changing AudioMixerGroup.
I am trying to change AudioSources's AudioMixerGroup to a new one via script and I am loading it the following way:
audioSource.outputAudioMixerGroup = Resources.Load("Resources/AudioMixerWithSound") ; //Here it can convert an object to explicit AudioMixerGroup.
//audioSource.AudioMixerGroup = Resources.Load("AudioMixer/AudioMixerGroup") as AudioMixerGroup; // Here AudioMixerGroup doesn't exist.
So how can I change the AudioSOurce's outputAudioMixeGroup?
There is really no Unity Asset named AudioMixerGroup. Notice that the only audio mixing asset you can create is AudioMixer if you go to Assets --> Create --> AudioMixer. If this is how you created the mixer then the resources file type to load is AudioMixer not AudioMixerGroup and the extension should be ".mixer".
Note that you don't include the resources folder name in the Resources.Load function. If the "AudioMixerWithSound" file to load is the Resources folder, you would use Resources.Load("AudioMixerWithSound") to load it instead of Resources.Load("Resources/AudioMixerWithSound"). Also, the extension ".mixer" is not included.
Loading the AudioMixer file from the Resources folder:
//Get the AudioSource
AudioSource audioSource = GetComponent<AudioSource>();
//Load AudioMixer
AudioMixer audioMixer = Resources.Load<AudioMixer>("AudioMixerWithSound");
//Find AudioMixerGroup you want to load
AudioMixerGroup[] audioMixGroup = audioMixer.FindMatchingGroups("Master");
//Assign the AudioMixerGroup to AudioSource (Use first index)
audioSource.outputAudioMixerGroup = audioMixGroup[0];
Note that where the AudioMixerGroup is found with FindMatchingGroups("Master"), if it is a child object, you can use / to access the child like you would with the GameObject.Find function. For example, FindMatchingGroups("Master/child"). See the doc for more info.
Related
I use unity3d and vs2019 to read a text file (txt) as follows:
public class MeshTest01 : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
string filePath = #"D:\Desktop\Unity\Mesh\77.txt";
string[] lines = File.ReadAllLines(filePath);
foreach (var item in lines)
{
Debug.Log(item);
}
//List<string> planesStr = TxtOperation.GetFaces2str(linesStr);
//Debug.Log(TxtOperation.GetFaceIndex(planesStr[0]));
}
}
The error information is as follows:
DirectoryNotFoundException: Could not find a part of the path "E:\project\GitHub\RobotSimulation\***D:\Desktop\Unity\Mesh\77.txt".
Why does the previous part of the file path appear
Honestly, I can't explain why this happens.
Usually yes, this would be one way of how to read an external file.
My guess would be that since your file is placed on a different drive the project might be sandboxed and therefore interprets the path as a relative one. Never tried to load files from different drives to be honest.
However, in general I would keep the files together with the project they belong to and place them
either in the Application.streamingAssetsPath in the editor in the folder Assets/StreamingAssets for files that shall be
read/write able for the editor
but readonly later in a build
or the Application.persistentDataPath for builds if you want to
write to them via code
or let the user change the content
externally afterwards
Then you would get your path using
var path = Path.Combine(Application.streamingAssetsPath, "SomeFolder", "77.txt");
or accordingly
var path = Path.Combine(Application.persistentDataPath, "SomeFolder", "77.txt");
For the streaming assets there are some special cases (e.g. on Android) where you need to read the file using UnityWebRequest.Get since it gets compressed.
Alternatively if it is an option for you you could also directly drag it into the Assets (or any folder below except special ones like StreamingAssets, Resources etc) and then directly drag it into a field via the Inspector using it as a (read-only) TextAsset
[SerializeField] private TextAsset meshFile;
and later access it's content via
var lines = meshFile.text.Split('/n');
Also I general: You should make a huge circle around the Resources!
Unity themselves strongly recommend to not use it! This and the reasons can be found in the Best practices.
Yes, I have read all the topics with similar problems.
However mine is not solved yet :(
So could you please take a look into it?
Like everyone else, I'm trying to change a sprite of an object via code.
The sprite file itself is in "Assets/Resourses" folder.
The import settings state the texture type of the imported file is "Sprite(2D and UI)".
I've tried the following methods:
gameObject.GetComponent<SpriteRenderer>().sprite = Resources.Load<Sprite>("1");
and
gameObject.GetComponent<SpriteRenderer>().sprite = Resources.Load("1") as Sprite;
and
Sprite s = Resources.Load("1") as Sprite;
gameObject.GetComponent<SpriteRenderer>().sprite = s;
and
Sprite s = Resources.Load<Sprite>("1");
gameObject.GetComponent<SpriteRenderer>().sprite = s;
All of them replace existing object sprite with "None(Sprite)", which I guess, means "null".
Any help would be really appreciated!
The sprite file itself is in "Assets/Resourses" folder.
That's the problem. The folder must be named Resources not Resourses. It's not Resource too.
It has to be named named Resources. Once you fix the folder name, you can use the snippet below to read the Sprite.
Sprite sprite = Resources.Load("1", typeof(Sprite)) as Sprite;
if the sprite is set to multiple mode then use this;
Sprite[] sprite = Resources.LoadAll<Sprite>("1") as Sprite[];
You can find other ways to load Sprites here.
I want to change the image that clicked image button.
so, I set a button and try to load a PNG file at assets/Resources/ PATH.
But it always return and it makes me massed up -_-.
Some of questions likes my situation, everybody answers 'try to move file to load assets/Resoucres PATH and my situation couldn't be fixed that way.
Here is my code. This function is load a NumCard_1.png file when clicked a image button. NumCard_1.png exists at assets/Resources folder.
void OnclkMe()
{
Sprite newSprite = Resources.Load<Sprite>("/NumCard_1") as Sprite;
// I already try ("NumCard_1") instead above.
if(newSprite==null)
{
Debug.Log("NULL"); // Always prints "NULL" -_-.
}
else
{
Debug.Log(newSprite.name);
}
}
When using Resources.Load in Unity, it uses a relative folder to "Resources"
every resource you intend to use at runtime must be located under /Resources, if it ain't there - create it.
after you create this base folder (under Assets) you can create subfolders by your own preference.
secondly, Resources.Load("/NumCard_1") as Sprite is kind of misused.
the generic method Resources.Load returns T so you can drop the "as Sprite" (it will act the same).
as Unity uses "Resources" as base folder you should remove the "/" before "NumCard".
if you use subfolder you might want to specify the path as "Cards/NumCard_1".
as per your code, after creating the folder Assets/Resources and placing the img in it, try the following:
Sprite newSprite = Resources.Load<Sprite>("NumCard_1")
Add your sprite in resources folder.
Change texture type to Sprite, and apply.
Sprite newSprite = Resources.Load("NumCard_1",typeof(Sprite)) as Sprite;
Maybe you don't set import config of that file into sprite? Normally png would be imported as texture, not sprite
First you should try to check it like this
var obj = Resources.Load("NumCard_1");
Debug.Log(typeof(obj));
If obj is not null, it would tell you what type it is. If it not sprite you would need to go to unity editor, select file, and change import type that png into sprite
ps Using generic mean you can just write is like this
var obj = Resources.Load<Sprite>("NumCard_1");
And obj will be sprite. If it not a sprite it would be null
Folder Name Must be named "Resourses" in asset
I'm able to change the text of a UILabel (named about) with the following:
using UnityEngine;
using System.Collections;
public class about : MonoBehaviour
{
void Start ()
{
UILabel lbl = GetComponent<UILabel>();
lbl.text = "Hello World!";
}
}
However things go awry when I want to load the label text from a text file in resources (Assets/Resources/about.txt)
lbl.text = Resources.Load(Application.dataPath + "/Resources/about") as String
So I'm not sure where I'm going wrong, and yes I have looked here.
Simply use this:
TextAsset mytxtData=(TextAsset)Resources.Load("MyText");
string txt=mytxtData.text;
and you can use the txt string to fulfill your requirement, just make sure that MyText.txt is in Assets > Resources
Have you tried one of these:
TextAsset mydata = Resources.Load("MyTexts/text", typeof(TextAsset));
TextAsset mydata = Resources.Load("MyTexts/text") as TextAsset;
Here, "MyTexts/text" is the asset name, which will actual refere the file text.txt.
The asset should be placed inside the Assets folder this way:
Assets/MyTexts/text
On the filesystem you will have:
.../Assets/MyTexts/text.txt
Don't use Application.dataPath or anything like that, you're loading a statically linked asset from the binary asset file.
The loaded mydata is binary. Use Encoding.ASCII.GetString(mydata.bytes) to get an actual string out of it.
var loaded_text_file = Resources.Load("mytexts/myfiletextname") as TextAsset;
string txt = loaded_text_file.text;
I was having a hard time loading 'TextAsset' files, until I discovered that only certain file extensions can be used. In my case I was trying to use '.yml', but unity will only read '.yaml'.
Full details here: https://docs.unity3d.com/Manual/class-TextAsset.html
I searched for alot of methods online and implemented them, but none of them worked. So I went to Unity docs. Here is a link hope it helps.
Unity Read Resource Read it carefully.
Edit:
here is a simple implementation:
Create Resources folder in Assets.
Place your text file in that folder(Resources).
code:
var textFile = Resources.Load<TextAsset>("file name only not path and no file extension(.txt)");
//store it in any List line by line(optional)
List<String> words = new List<string>(textFile.text.Split('\n'));
I am working in XNA 4.0 Game Studio (C#), and I am trying to load an image using the LoadContent() method. I have loaded numerous image files into this game and they all work 100% fine, but for some reason, XNA will not open files inside one of my loadContent methods. Here is the method:
protected override void LoadContent()
{
//spriteBatch = new SpriteBatch(GraphicsDevice);
//Sets up an array of textures to be used in the Icon class
Texture2D[] icons = new Texture2D[24];
#region Loading talent textures
//These are all of the icons that need to be loaded for the talents
//Paladin
icons[0] = Content.Load<Texture2D>(#"C:\Users\Student\Desktop\Dropbox\Public\platformer\Platformer\Content\Talents\blade_of_light3.jpg");
icons[1] = Content.Load<Texture2D>("Talents\\divine_grace");
icons[2] = Content.Load<Texture2D>("Talents\\divine_storm");
icons[3] = Content.Load<Texture2D>("Talents\\hammer_of_the_righteous");
icons[4] = Content.Load<Texture2D>("Talents\\healing_hands");
icons[5] = Content.Load<Texture2D>("Talents\\heavenly_fury");
icons[6] = Content.Load<Texture2D>("Talents/momentum_of_light");
icons[7] = Content.Load<Texture2D>("Talents/retribution");
icons[8] = Content.Load<Texture2D>("Talents/righteous_fury");
icons[9] = Content.Load<Texture2D>("Talents/sanctuary");
icons[10] = Content.Load<Texture2D>("Talent/searing_light");
icons[11] = Content.Load<Texture2D>("Talent/wrath_of_the_heavens");
//Warrior
icons[12] = Content.Load<Texture2D>(#"Talents\bloodstorm");
icons[13] = Content.Load<Texture2D>(#"Talents\bloodthirst");
icons[14] = Content.Load<Texture2D>(#"Talents\die_by_the_sword");
icons[15] = Content.Load<Texture2D>(#"Talents\furious_blades");
icons[16] = Content.Load<Texture2D>(#"Talents\unleash_rage");
icons[17] = Content.Load<Texture2D>(#"Talents\lifeblood");
icons[18] = Content.Load<Texture2D>(#"Talents\red_like_my_rage");
icons[19] = Content.Load<Texture2D>(#"Talents\eternal_thirst");
icons[20] = Content.Load<Texture2D>(#"Talents\bladesurge");
icons[21] = Content.Load<Texture2D>(#"Talents\bathed_in_blood");
icons[22] = Content.Load<Texture2D>(#"Talents\bladerunner");
icons[23] = Content.Load<Texture2D>(#"Talents\bloodfury");
icons[24] = Content.Load<Texture2D>(#"Talents\grapple_chain");
#endregion
As you can see, I have tried using the ENTIRE file location. It finds the file, but throws an exception when the LoadContent() method is called and says "Cannot open file blade_of_light3."
I do not get any errors about escape paths or anything like that, and I have used this sort of file path for other images, and they work fine. It's just here, in this class, in this loadContent method, that they won't work.
The Content.Load methods does not load files, it loads specialized content or assets. Have a look at this.
You can't load files directly, you can only load assets. These assets are generated via the content pipeline.
This is mainly to provide an abstract layer for content. Because XNA is platform independent, and on one machine you may be use a bigger image or different image, you only need to change the asset in the pipeline and can reuse the code.
Just to add to dowhilefor's excellent answer, if you want to load a raw .jpg file (or .png), you can do so like this:
using(var s = File.OpenRead(fileName))
{
Texture2D texture = Texture2D.FromStream(GraphicsDevice, s);
}
Unlike when you load something using ContentManager, you "own" it in this case. This means you are responsible for calling Dispose() on it in UnloadContent.
Also unlike when you go through the content pipeline (using the default settings), the texture that you load will not have premultiplied-alpha. You need to apply premultiplication yourself, or render it with BlendState.NonPremultiplied.
Of course, unless you are unable to for some reason (eg: you're downloading images from the internet, or you're letting your end user pick them), you should use the content pipeline.