What I'm trying to do is contain an audio file in a folder (under Resources) where I can drop any qualifying audio file in the specified folder and have the numerous triggers in my program read from that single point (which is why my AudioClip below is public static so I can reference it). Currently, the same audio file works throughout the program, but to change the file requires manual redefining in the Inspector which my eventual client won't have access to, and besides is tedious due to the numerous reference points that exist.
Here's what I have so far:
public static AudioClip BGM;
public AudioSource BGMSource;
private string formatted1;
void Start()
{
foreach(string file in System.IO.Directory.GetFiles(Application.dataPath+"/Resources/Audio/BGM"))
{
if(file.EndsWith(System.IO.Patch.GetExtension(".mp3")))
{
formatted1 = file.Replace(".mp3",string.Empty);
BGM = Resources.Load<AudioClip>(formatted1);
//BGM = (AudioClip)Resources.Load(formatted1,typeof(AudioClip)); <--same result with this
Debug.Log("found: "+formatted1);
}
}
if(BGM == null)
{
Debug.Log("Yeah, its null");
}
BGMSource.PlayOneShot(BGM, .9f);
if(BGMSource.isPlaying != true)
{
Debug.Log("I'm not playing");
}
}
So as is, this just doesn't play, no error messages. Turns out BGM is null. The Debug says as so, but if I were to add a Debug call for BGMSource.clip.name, it will fully error out with a NullReferenceException on that Debug.
The Debug for the formatted1 string (File path and name), it does present the correct file called Test.mp3 ("C:/...Resources/Audio/BGM\Test") formatted without the ".mp3" as was recommended from another site. I did try with the .mp3 extension on, didn't seem to matter, still didn't play. I also tried with a .wav file and .ogg file, same result (note: all files were fine if I attached as a public AudioClip manually as also the AudioSource as written above would play in that case, but as I lead with, we don't want that for this case). Yes, all test audio files were in the directory /Resources/Audio/BGM.
Another site said something about adding to the top of the file [RequireComponent(typeof(AudioClip))] or [RequireComponent(typeof(AudioSource))]but that did nothing.
Lastly, this program will eventually be given to a group that won't have source access so they MUST be able to swap the audio file by dropping any .mp3 in Resources/Audio/BGM for auto play.
Any help is welcome, thanks!
First a general note: Never use + "/" for system file paths! Rather sue Path.Combine which automatically inserts the correct path separators according to the platform it is running on
string file in System.IO.Directory.GetFiles(Path.Combine(Application.dataPath, "Resources", "Audio", "BGM"))
Then please read the documentation of Resources.Load!
It requires your file(s) being placed inside a folder called Resources which is compiled into the application build and therefore can not be changed afterwards. This seems to be the case for you.
It does not take a full system path like you pass in since Directory.GetFiles returns
An array of the full names (including paths) for the files in the specified directory
but rather expects a path within all Resources folders - yes you can have multiple ones.
Let's say e.g. you put your files in a structure like
Assets
|--Resources
| |--someFile.mp3
|
|--SomeOtherFolder
| |--Resources
| | |--someOtherFile.mp3
| | |--ASubFolder
| | | |--yetAnotherFile.mp3
Then you would address these by using
Resources.Load<AudioClip>("someFile");
Resources.Load<AudioClip>("someOtherFile");
Resources.Load<AudioClip>("ASubfolder/yetAnotherFile");
since when build all Resources are packed together.
So in your case it should be
Resources.Load<AudioClip>("Audio/BGM/" + formatted1);
where you have to make sure that formatted1 is not a full path but only the filename! You can simply use Path.GetFileNameWithoutExtension so you don't even need your replace
var formatted1 = Path.GetFileNameWithoutExtension(file);
It is bad ^^
In their Best Practices for the Resources folder Unity themselves recommend
Don't use it!
However
Since it is not recommneded to use the Resources at all I would rather recommend:
If you don't want to change them later
You can't change the Resources afterwards for e.g. replacing a file. So if you can't change the files later anyway, then why not rather directly reference them in the places where they are needed later?
Simply put your audio files in a folder that is not Resources and reference them in your scripts directly where you need them:
// Simply drag&drop the clip into this field via the Inspector in Unity
[SerializeField] private AudioClip someClip;
If you want to change them later
In case you actually would like to be able to replace them later also after a build you could instead use UnityWebRequestMultimedia.GetAudioClip which can also be used to load files from a system file on runtime. For this you wouldn't put your files into the Resources or any other folder but rather either the StreamingAssets or the Application.persistentDataPath.
I usually go:
In the editor use StreamingAssets folder so all stuff lies inside the project and access it via Application.streamingAssetsPath
In a build first check if file exists in Application.persistentDataPath
If not copy it from Application.streamingAssetsPath and store it into Application.persistentDataPath
otherwise simply load it from Application.persistentDataPath
Modified API Example
[RequireComponent(typeof(AudioSource))]
public class AudioExample : MonoBehaviour
{
[SerializeField] private AudioSource _audioSource;
public List<AudioClip> LoadedAudioClips = new List<AudioClip>;
private List<UnityWebRequest> _runningWebRequests = new List<UnityWebRequest>();
private void Awake()
{
if(!_audioSource) _audioSource = GetComponent<AudioSource>();
}
private void Start()
{
StartCoroutine(GetAudioClip());
}
private IEnumerator GetAudioClip()
{
foreach(string file in System.IO.Directory.GetFiles(Path.Combine(Application.persistentDataPath, "Audio", "BGM"))
{
if(!file.EndsWith(System.IO.Patch.GetExtension(".mp3"))) continue;
UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip("file:///" + file, AudioType.MPEG);
{
_runningWebRequests.Add(www);
www.Send();
}
}
while(_runningWebRequests.Count > 0)
{
foreach(var www in _runningWebRequests.Where(www => www.isDone))
{
_runningWebRequests.Remove(www);
if (www.isError)
{
Debug.LogWarning(www.error);
}
else
{
var clip = DownloadHandlerAudioClip.GetContent(www);
if(clip == null)
{
Debug.LogError("Huh?!");
}
else
{
LoadedAudioClips.Add(clip);
}
}
}
yield return null;
}
}
}
Also saw you comments so:
StreamingAssets is also a special folder you can store files in you want to read in on runtime. It is local. Also this folder is not "visible" from the outside and can not be altered later.
If you need to be able to alter stuff later (like e.g. also saving files) you will always need to use the Application.persistentDataPath instead.
Related
My game includes image files and json configuration files that I would like to make accessible in the deployed game's folder structure so that players can easily edit or swap them out.
I have considered/tried the following approaches:
My initial approach was to use the Resources folder and code
such as Resources.Load<TextAsset>("Rules.json"). Of course,
this did not work as the resources folder is compiled during builds.
I investigated the Addressables and AssetBundle features, but they do not seem aimed at solving this problem.
After asking around, I went for using .NET's own file methods, going
for code like File.ReadAllText(Application.dataPath + Rules.json). This seems like it will work, but such files are still not deployed automatically and would have to manually be copied over.
It seems that the StreamingAssets folder exists for this, since the manual advertises that its contents are copied verbatim on the target machine. I assume that its contents should be read as in the previous point, with non-Unity IO calls like File.ReadAllText(Application.streamingAssetsPath + Rules.json)?
So yeah, what is the 'canonical' approach for this? And with that approach, is it still possible to get the affected files as assets (e.g. something similar to Resources.Load<Sprite>(path)), or is it necessary to use .NET IO methods to read the files and then manually turn them into Unity objects?
After asking the same question on the Unity forums, I was advised to use the StreamingAssets folder and told that it is necessary to use .NET IO methods with it.
An example for how to load sprites as files using standard IO can be seen here: https://forum.unity.com/threads/generating-sprites-dynamically-from-png-or-jpeg-files-in-c.343735/
static public Sprite LoadSpriteFromFile(
string filename,
float PixelsPerUnit = 100.0f,
SpriteMeshType type = SpriteMeshType.FullRect)
{
// Load a PNG or JPG image from disk to a Texture2D, assign this texture to a new sprite and return its reference
Texture2D SpriteTexture = LoadTexture(filename);
Sprite NewSprite = Sprite.Create(
SpriteTexture,
new Rect(0,
0,
SpriteTexture.width,
SpriteTexture.height),
new Vector2(0, 0),
PixelsPerUnit,
0,
type);
return NewSprite;
}
static private Texture2D LoadTexture(string FilePath)
{
// Load a PNG or JPG file from disk to a Texture2D
// Returns null if load fails
Texture2D Tex2D;
byte[] FileData;
if (File.Exists(FilePath))
{
FileData = File.ReadAllBytes(FilePath);
Tex2D = new Texture2D(2, 2);
// If the image is blurrier than what you get with a manual Unity import, try tweaking these two lines:
Tex2D.wrapMode = TextureWrapMode.Clamp;
Tex2d.filterMode = FilterMode.Bilinear;
// Load the imagedata into the texture (size is set automatically)
if (Tex2D.LoadImage(FileData))
{
return Tex2D; // If data = readable -> return texture
}
}
return null;
}
Okay, so I've been struggling around and searching for a while, saw a lot of different posts, but I did not find answer to my question.
My problem:
I have a scene in Unity with nothing in it, everything is created proceduraly and randomly on game start, and of course I want the player to be able to save his progress. I have found ways of saving progress in Unity, but everything was about writing a script for each class or object I want to save, but these seem to me inefficient, since in my game, there are randomly generated houses and buildings (which would be relatively easy to save), but there can also be objects placed inside these buildings and so on. Also later I plan on adding characters, which also need to be saved (like where they are, what are they holding and such). And as I mentioned, writing a save and load script for each object seems inefficient to me, since I'm used to Java's serializtaion, where I just write my Main Object containing all data to a file, so I'm looking for some easier ways to do so. Possibly a way to save entire scene state and then on loading just load the scene instead of generating it from scratch.
My Question:
Is there a way to save whole scene with all objects and information about them and then load it?
Thank you in advance!
There's no built-in method by which you can "save a scene" during runtime and then reload it later. In a Unity build, scenes are stored in a non-editable format, meaning that whenever you load a scene it will load up with the same format as it was built. This is a good thing, because you don't want to edit the contents of your build in a deployed game.
Now, that doesn't mean that a scene can't contain logic to configure itself differently. In fact, it sounds like that's what you're doing. The goal instead is to store the contents into a save file.
Consider switching your mentality from "I want to load a scene that generates random gameplay" to "I want to load a scene that configures itself based on a file." This is a layer of abstraction that gives greater control over what happens when you load your scene.
I would suggest creating a JSON configuration file that stores your important information, something like this might do:
{
"house_locations": [
{
"position": "(0, 0, 0)",
"objects": []
},
{
"position": "(10, 10, 10)",
"objects": []
}
],
"characters": [
{
"position": "(0, 0, 0)",
"inventory": [
{
"item_name": "knife"
},
{
"item_name": "shovel"
}
]
}
]
}
This is just a simple example, as you'll have to add the important data you want to represent your game.
Next, all you have to do when you want to start your game is to do one of the following things:
Are you starting a new game? => Generate a random configuration file, then use that to populate your scene.
Are you loading a saved game? => Use the saved configuration file to populate your scene.
You'll need some kind of WorldBuilder script to handle this. In your scene, you can have something like the following:
public class WorldBuilder : MonoBehaviour
{
// This is the actual contents of the world, represented as a JSON string.
private string _json = "";
public void BuildWorld(string configFilePath)
{
_json = LoadConfiguration(configFilePath);
BuildWorld(_json);
}
public void GenerateWorld()
{
_json = GenerateConfiguration();
BuildWorld(_json);
}
public void SaveWorld(string targetFilePath)
{
// Save the contents of _json out to a file so that it can be loaded
// up again later.
}
private string LoadConfiguration(string configFilePath)
{
// Load the actual file and return the file contents, which is a JSON string.
}
private void BuildWorld(string json)
{
// Actually build the world using the supplied JSON.
}
private string GenerateConfiguration()
{
// Return a randomly generated configuration file.
}
}
This approach separates the problem of saving the contents of the scene and generating the contents of the scene, making the code easier to write and maintain.
I do not know how to build a scene save patternor principles.
But there is a plugin which save scene in play mode, you may configure it according to your project.
https://assetstore.unity.com/packages/tools/utilities/autosaver-don-t-waste-time-anymore-54247
I would name 'LoadConfiguration' to 'LoadWorld'. Actually, I'd name it 'WorldSave' and 'WorldLoad' so it all matches up alphabetically.
Also, have loading be asynchronous:
public IEnumerator WorldLoad(string localWorldFilePath)
{
string filePath = Application.persistentDataPath + "/" + localWorldFilePath + ".json");
string lines = null;
//Loading the level loop:
using (SteamReader streamReader = new StreamReader(filePath,Encoding.UTF8))
{
lines += streamReader.ReadToEnd();
if (UnityEngine.Random.Range(0f,20f) > 15f) //< - probably a fancier way of doing this part)
yield return new WaitForEndOfFrame();
}
//Okay, we're done loading so return this:
yield return lines;
}
In fact, have saving be asynchronous too, using StreamWriter and make sure it's also encoded in UTF8, you can't just use File.Save and File.Load in other words.
Another idea, encrypt your files if you don't want modding (but people will just decrypt it anyway).
Start the coroutine somewhere else, the lower you make that '15f' the more it'll lock up your game, the higher you make it the less it will but the slower it'll go. There's a way to do it on a separate thread or something but I'm not an advanced programmer.
worldBuilder.StartCoroutine(WorldLoad);
TIP 1:
Ideally you wanna create your own scripting language through a console, if the idea of real-time custom scene file loading and saving is that you can create and edit your levels while the actual game is running so that you're bypassing using Unity as a level editor for example.
In other words you could press ~ and bring a console up and type 'WorldLoad(worldNameGoesHere)' and it'll load the world in your games built folders.
There's also a way using an editor script you can actually hook in and override Unity's standard 'Scene Save', in case you wanna do that also.
TIP 2:
Also make sure you encode in UTF8 format like above, saving and loading so you don't have it become a pain later when you want to implement asian languages like Japanese, Chinese, etc...
I'm using the A* pathfinding algorithm for my 2D game (from my understanding, Unity Nav Meshes don't work in 2D). I would like to be able to pre-calculate navigation grids for all of my scenes, and save them in resource files that can be loaded whenever the player enters a new scene. Rather than having to remember to click "calculate" for every scene -- and remember to recalculate all of my scenes if I make a change to my navigation grids -- I want to be able to programatically have the Unity Editor iterate though each scene and calculate the grids.
Is there a way to create a command in the Unity editor that will iteratively open each scene in the editor and run a method on a MonoBehaviour that's in the scene? Alternatively, is there another way to accomplish what I'm trying to do?
Yes you can!
In editmode you can't use SceneManager but have to use the EditorSceneManager.
First of all you need the scenes you want to iterate.
Could be e.g. a public static field with a list of SceneAsset in the Inspector where you simply reference the scenes
public static List<SceneAsset> Scenes = new List<SceneAsset>();
or you could get them by script e.g. for only use the scenes added to the build settings using EditorBuildSettings.scenes
List<EditorBuildSettingsScene> Scenes = EditorBuildSettings.scenes;
For both you can get a list of the scene paths e.g. using LinQ Select (this is basically a kind of shortcut for a foreach loop) and AssetDatabase.GetAssetPath like
List<string> scenePaths = Scenes.Select(scene => AssetDatabase.GetAssetPath(scene)).ToList();
for the EditorBuildSettingsScene from EditorBuildSettings.scenes you can also simply use
List<string> scenePaths = Scenes.Select(scene => scene.path).ToList();
Now you can iterate over them all and do your stuff by using EditorSceneManager.OpenScene, EditorSceneManager.SaveScene and EditorSceneManager.CloseScene (and if you need it AssetDatabase.SaveAssets)
foreach(string scenePath in scenePaths)
{
// Open a scene e.g. in single mode
var currentScene = EditorSceneManager.OpenScene(scenePath);
/* Do your calculation for currentScene */
// Don't know if it makes changes to your scenes .. if not you can probably skip this
EditorSceneManager.SaveScene(currentScene);
// Finally Close and remove the scene
EditorSceneManager.CloseScene(currentScene, true);
}
// you might be doing changes to an asset you want to save when done
AssetDatabase.SaveAssets();
Before starting you should probably ask to save the current open scene(s) using EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo
if(EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo())
{
// Saved => the foreach loop here
}
else
{
// aborted => do nothing
}
Than in order to finally start that method the simplest would be to add a [MenuItem]
public static class Calculation
{
[MenuItem("YourMenu/RunCalculation")]
public static void RunCalculation()
{
// all the before mentioned snippets here
// depending how exactly you want to do it
}
}
This will add a new menu YourMenu with one entry RunCalculation to the top menubar of the Unity Editor.
Note:
Since this uses a lot of types (EditorSceneManager etc) that only exist in the UnityEditor namespace you should either place the whole script in an Editor folder (so it is ignored in the final build) or use pre-processors like
#if UNITY_EDITOR
// ... code here
#endif
so in the build the code is also ignored.
Note that I'm assuming so far you also did your calculation in editmode. The thing is if this calculation relies somewhere aon any Start or Awake method you have to call it manually from that editorscript before running the calculation.
I've seen similar questions all over the internet, but none seem to apply to my situation.
I have a very simple project with two scenes: MainMenuScene and OtherScene. OtherScene is nothing but a blank canvas, and MainMenuScene just has a button which is meant to be used to navigate to OtherScene. The Main Camera has the following script attached to it:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class LaunchScene : MonoBehaviour {
public void LaunchSceneOnButtonClick(int index)
{
SceneManager.LoadScene(index);
}
public void LaunchSceneOnButtonClick(string sceneName)
{
SceneManager.LoadScene(sceneName);
}
}
and in the OnClick() of the button, this script is called. I have made sure to add both levels to the Build Settings.
If I call the version of the LanchSceneOnButtonClick which takes an integer argument (and specify the appropriate value in the OnClick() method) then the desired scene loads.
However, if I call the version which takes a string argument and use the exact name of the scene I want to load (and I've quadruple checked that it is indeed the exact string, that the string name has no spaces or hidden characters, and have copy pasted the scene name into the OnClick() argument field) the scene does not load and instead I get the error message
Scene "OtherScene" couldn't be loaded because it has not been added to
the build settings or the AssetBundle has not been loaded.
Since using the scene index works, we know it was added to the Build Settings properly, so I reason that there is some issue with the scene name. But I've copied it exactly. I want to avoid using the full path of the scene in case I later decide to move scenes around to different folders, so what are my options here?
Thanks in advance.
EDIT:
Adding screenshots.
Scene in folder structure:
Scenes in build settings:
OnClick() input:
Keep in mind I've also tried the input to OnClick() with and without quotation marks.
The only possible problems are these:
The string passed is different from the scene name; bear in mind, the string used in LoadScene is not case sensitive, i.e. you can use OtherScene, OTHERscene, etc.
The scene in the build settings is not active (i.e. with the checkmark on the left disabled).
The scene isn't present at all in the build settings.
The full path of the scene is irrelevant btw, you can have OtherScene inside any dir/subdir in the Assets, and you'll need only the name of the scene. You need the full path of the scene only if you have more than scene with the same name in different paths (and anyway you shouldn't, it's such an obvious terrible practice).
EDIT: You say that you tried even without " (as you should do, when entering string fields in the inspector you don't need them), what happens if you modify the method body to:
public void LaunchSceneOnButtonClick(string sceneName)
{
SceneManager.LoadScene("OtherScene");
}
Try this and report back what happens please.
I had also the problem that
public void loadScene(string scene)
{
SceneManager.LoadScene(scene);
}
did not work for me in the first place. What did I do? I'm saving the names of my scenes in a List (read from a file) and from that List I choose the scene I need.
But somehow the reading progress seems to give me some unwanted characters so the scene loading does not work as intended. When I added .Trim() it started to work.
For a better understanding, here's an example:
string s = sceneList[1].Trim();
this.loadScene(s);
public void loadScene(string scene)
{
SceneManager.LoadScene(scene);
}
So make sure that you get rid of unwanted characters.
Is there a way to assign multiple assets to multiple variables on the inspector???
My case is this, I have 5 objects, those objects have a script wich have around 1200 variables used to play SFXs. When Unity compile the script I have to manually drag and drop the SFX from the assets to the variable on the inspector, or go to the inspector, scrol to the variable, click the dot and then select the SFX file from the window.
Is there a way to speed this up?
You should create a public List of Audio Sources which will appear in inspector. Lock the inspector by clicking look in right top.
Now select all the files from Project and drag on list. All files will be added to list. Now if you want a specific file you can find the file by its name for example:
AudioSource GetAudioSource(string SourceName)
{
return audioSourceList.Find(item => item.Name == SourceName);
}
Use the Resources.LoadAll method to access all the assets from the path parameter via scripting. Probably put that method call in Start. Might have to rename the files to pull the right order from the LoadAll method if they result in some alternate order.
EDIT: Here's some example code...
(NOTE: Loads from Resources/Sound/SFX folder)
For reference: http://docs.unity3d.com/ScriptReference/Resources.LoadAll.html
public class YourClassNameGoesHere : MonoBehaviour
{
Public AudioClip[] BA;
void Start ()
{
BA = (AudioClip[]) Resources.LoadAll("Sound/SFX");
}
}
I found a solution for this problem. I must say, it's not perfect, in fact, it should not be used unless is absolutely necessary.
To speed up the assign you could do this:
Create a variable
public AudioClip ma, me, mi, mo, mu;
At Start() add
ma = Resources.Load("Sound/SFX/MA") as AudioClip;
me = Resources.Load("Sound/SFX/ME") as AudioClip;
mi = Resources.Load("Sound/SFX/MI") as AudioClip;
mo = Resources.Load("Sound/SFX/MO") as AudioClip;
mu = Resources.Load("Sound/SFX/MU") as AudioClip;
After compile the public variables will be available on the Inspector as empty variables, but, on runtime the variables will be filled with the content of the folder Resources/Sound/SFX (Assets\Resources\Sound\SFX).
Why shouldn't be use unless necessary?, first, it's a bad practice; second, it's a cheap trick that comes at a price (on mobile devices it load all the resources so will consume RAM fast). In my test, all my sound clips take as much as 169 MB. On PC it's not much of a problem, but if your target is Mobile games, this is something to take into consideration. And third, on web player, ALL resources will be streamed first.
On a side note, this cheap trick ignores the way Unity handles assets. Unity force you to assign assets manually because if the asset is not use, it will not be integrated into the build. This trick force everything to be loaded and be integrated into the final build, used or no. On the other hand, if you are assign it, you will use it... right?
The answer and example given by #Jayson Ash lead me to the right direction.