Using Firebase functions in an editor script - c#

I've done a bit of research and i'm kind of strugguling right now.
I want to use Firebase Database functions to write datas in an editor script on Unity.
I managed to read/write in the database during the run time pretty easly (the doc online is great !), but when i try to do it on edit time, it's not working.
I've got a pretty explicit error : "Notice that DontDestroyOnLoad can only be used in play mode and, as such, cannot be part of an editor script."
Considering this error, it seems impossible to use Firebase functions here. But did someone manage to use it ?
The only solution I could think of right now is writing a python script and launching it from the unity editor, but that's not really conviniant having to deal with plenty of languages in an industrial project (unless you have no choice).
Thanks for reading and sorry for all the grammatical mistakes !
Louis

At first you should initialize firebase with new instance of FirebaseApp with unique name. I do it like this:
FirebaseApp firebaseApp = FirebaseApp.Create(
FirebaseApp.DefaultInstance.Options,
"FIREBASE_EDITOR");
The second is setup references (DatabaseReference, StorageReference etc.) with this firebaseApp instance and use it only after FirebaseApp.CheckAndFixDependenciesAsync()
Overall code will look like this:
public static void Initialize(bool isEditor = false)
{
if (isEditor)
{
FirebaseApp firebaseApp = FirebaseApp.Create(
FirebaseApp.DefaultInstance.Options,
"FIREBASE_EDITOR");
firebaseApp.SetEditorDatabaseUrl("https://project.firebaseio.com/");
FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task =>
{
if (task.Result == DependencyStatus.Available)
{
database = FirebaseDatabase.GetInstance(firebaseApp).RootReference;
storage = FirebaseStorage.GetInstance(firebaseApp).RootReference;
auth = FirebaseAuth.GetAuth(firebaseApp);
}
else
{
Debug.LogError(
"Could not resolve all Firebase dependencies: " + task.Result);
}
});
}
else
{
FirebaseApp.DefaultInstance.SetEditorDatabaseUrl("https://project.firebaseio.com/");
database = FirebaseDatabase.DefaultInstance.RootReference;
storage = FirebaseStorage.DefaultInstance.RootReference;
auth = FirebaseAuth.DefaultInstance;
}
IsInitialized = true;
}
Initialize SDK for editor before get/set data:
FirebaseManager.Initialize(true);
Then after CheckAndFixDependenciesAsync callback you can use Firebase in editor scripts.

Related

Access item inside Unity sharedassets.assets file programmatically in C# Mono

I'm working on a Cities: Skylines mod and I want to access the sharedassets.assets file(s) the game has in the Data folder programmatically to get a mesh/prefab.
I've found a tool called Unity Assets Bundle Extractor (UABE) and it is able to open up these files and extract the mesh.
Is there a way to extract a mesh from the sharedassets programmatically with C# code like UABE does?
I've looked in the Unity documentation but so far only have seen this page (not sure if relevant): https://docs.unity3d.com/ScriptReference/AssetBundle.LoadFromFile.html
I tried adapting the code from there but I haven't had any success so far, only have had not found error messages
var myLoadedAssetBundle = AssetBundle.LoadFromFile(Path.Combine(Application.dataPath, "sharedassets11"));
Is there a way to achieve this? Thanks
Look at the API for AssetBundle.LoadFromFile.
There is a second method AssetBundle.LoadAsset (or alternatively also maybe AssetBundle.LoadAllAssets) you will need:
var myLoadedAssetBundle = AssetBundle.LoadFromFile(Path.Combine(Application.dataPath, "sharedassets11"));
if (myLoadedAssetBundle == null)
{
Debug.Log("Failed to load AssetBundle!");
return;
}
var prefab = myLoadedAssetBundle.LoadAsset<GameObject>("NameOfTheAccordingObject");
Instantiate(prefab);
myLoadedAssetBundle.Unload(false);

I cannot get Xamarin to play small media files

Using an android scanner device, running KitKat.
Using Xamarin in Visual Studio Enterprise 2017, 15.9.9.
I need to generate a "Success" or "Error" sound, based on the content of the scanned barcode.
I have two files: "Success.mp3" and "Error.wav", neither of which will play.
Since this should be a very simple process, I am trying to use Android's MediaPlayer class, rather than add some NuGet package.
I am using Dependency Injection to properly run the Android code, since Xamarin does not have any sort or media API.
I instantiate Android's MediaPlayer as variable "player", and it does successfully instantiate, but as soon as I attempt to do anything with it, it throws a Null Exception error and the value of "player" displays as Null.
I have been experimenting with different ways to do this and have copies of the sound files stored both in the Assets folder, and the Resources/Raw folder (see below).
Here is my method:
public void PlaySound(string soundType) {
var filename =
global::Android.App.Application.Context.Assets.OpenFd(soundType);
if (player == null) {
MediaPlayer player = new MediaPlayer();
}
//This is where the error happens
player.SetDataSource(filename);
player.Prepare();
player.Start();
}
I have also tried the last three lines as the following, with the same result:
player.Prepared += (s, e) => {
player.Start();
};
player.SetDataSource(filename.FileDescriptor, filename.StartOffset,
filename.Length);
player.Prepare();
I have also attempted to utilize what so many people demonstrate as the way to do this, but it does not work for me. This is where the file must be stored in Resources/Raw:
player = MediaPlayer.Create(global::Android.App.Application.Context,
Resource.Raw.someFileName);
Whatever value that you use for "someFileName", all Visual Studio gives you is "'Resource.Raw' does not contain a definition for 'someFileName'".
Resource.designer.CS does contain entries for both files:
public const int Error = 2131230720;
public const int Success = 2131230721;
Expected results: sound, or some meaningful error message that puts me on the right path.
I am still relatively new to Xamarin and am probably missing something that would be obvious to veteran eyes. I have tried so many other things, most of which are not mentioned here, grasping for some straw. This should be simple, but is proving otherwise. Thank you for any help that you can provide.

Google Play Games returns false on Social.localUser.Authenticate

Hello: I've been wrestling a bit with getting my app to authenticate. I've deployed the APK to my Galaxy and the following happens: Unity game opens, "Connecting to..." dialog appears, "Google Play" green dialog appears, dialog disappears with loading indicator and then I get a "false" result.
I have the following in Start():
PlayGamesPlatform.Activate();
PlayGamesPlatform.DebugLogEnabled = true;
AuthenticateGoogle();
And the following in AuthenticateGoogle():
private bool AuthenticateGoogle()
{
isAuthorized = false;
Social.localUser.Authenticate((bool result) => {
isAuthorized = result;
if (!result)
{
GameObject.Find("errText").GetComponent<Text>().text = result.ToString();
}
});
return isAuthorized;
}
I created a new Keystore using the Unity UI, entered the password and built the .APK. I then created a new application in the Google Play Console and uploaded the .APK to it. I next created a new Game Service and linked the app, allowing it to Trust the application. I created a leaderboard. I ensured my user is in the Testing section. Lastly I copied the XML from the Get resources section under leaderboard to my Unity project and built the project, copying to my phone.
Any ideas? Any other things I can do to troubleshoot authentication versus a true/false result?
I assume that you are testing it on your android phone.
You should try adding this to your android mainfest:
<activity android:name="com.google.games.bridge.NativeBridgeActivity" android:theme="#android:style/Theme.Translucent.NoTitleBar.Fullscreen" />
You can create custom mainfest in Assets/Plugins/Android/AndroidMainfest.xml
Add yourself to testers on Google Play Console (if the app is in beta) and download it directly through google play. (not test build and run)
To track errors like this you can use a tool https://assetstore.unity.com/packages/tools/log-viewer-12047 It's simple to use and you can understand what went wrong. Hope it'll help :)
EDIT:
I'm using different method, but it shouldn't make a difference:
public bool ConnectToGoogleServices()
{
if (!isConnectedToGoogleServices)
{
{
Social.localUser.Authenticate(success =>
{
isConnectedToGoogleServices = success;
});
}
}
return isConnectedToGoogleServices;
}

Update C# code through website or database

I've searched through the web and seen a lot of talk about a WWW method of retrieving content from a web server or a database and using values but I would like a method where I don't have to continuously update my code in monodevelop and then build the projects as big projects sometimes take up to an hour to build so basically patching over a server.
So can the WWW method be used to do this? Like for instance lets say I have a code like this
int level;
int currentLevel;
if(level != currentLevel){
level = currentLevel;
}
Now this code is having complications because the level is not always up to date and I have to change methods into something like this so tht the level stays updated
int level;
int currentLevel;
private void Update(){
if(level != currentLevel){
level = currentLevel;
}
}
Now instead of rebuilding my entire project I would like to put this in maybe a database or some sort and then when the game launches it checks the database to make sure the code matches the code on the database if the code matches then it starts the game if not it updates
FYI I am building for WebGL HTML5
You can't do that. What you can do is to make make a decision based on what you receive from WWW but the action to do must exist already before it can used. You can't create a new action during run-time.
For example, make decision if ad should be displayed in your app.
WWW www = new WWW("url");
yield return www;
if(www.text=="AdEnabled"){
displayAd();
}
You can also run JavaScript code from Unity but that's not helpful to your question. You can't do more than that.

MagneticStripeReader.GetDefaultAsync(); returns null

I have a usb connected MSR reader and i am trying to get it by using the sample codes proveded in here. This works fine but the problem is when i add the same code to my app it doesn't work. GetDefaultAsync returns null.
private static MagneticStripeReader _reader = null;
public static async void StartRead()
{
if (await CreateDefaultMagneticStripeReaderObject())
{
....
}
}
private static async Task<bool> CreateDefaultMagneticStripeReaderObject()
{
if (_reader == null)
{
_reader = await MagneticStripeReader.GetDefaultAsync();
if (_reader == null)
return false;
}
return true;
}
My code is like above, very similer to sample but it doesnt work. Also i've added the device capability of pointOfService. So that is not the case.
I was in the exact same situation and I spent the last 5 hours, finally I know what was going on. You are missing a capability in the Package.appxmanifest
'pointOfService' is the capability you want to include. This capability does not show in the UI and therefore I could not find any difference between my broken project and Microsoft's sample project. You can not add that capability using the UI. You have to manually add it by modifying the XML file.
The sample project by Microsoft have it too
https://github.com/Microsoft/Windows-universal-samples/blob/master/Samples/MagneticStripeReader/cs/Package.appxmanifest#L53
Make sure the card reader is in HID mode and not Keyboard emulation mode. That was one of my problems.
To do this is really wonky. MagTek has a ActiveX control on their website to assist us... because ActiveX is awful, you can only use it with InternetExplorer (it won't even work with Edge.)
go here in IE: https://www.magtek.com/changemode/
Enable active X when it pops up, and you can change from hid to keyboard and back.

Categories

Resources