I want to get an image from my firebase storage project in unity and this is the code I have to get an image:
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using System.Threading.Tasks;
using UnityEngine.Networking;
using Firebase;
using Firebase.Extensions;
using Firebase.Storage;
public class ImageLoader : MonoBehaviour
{
public RawImage rawImage;
private FirebaseStorage storage;
private StorageReference storageReference;
private Texture2D tex;
private void Start()
{
storage = FirebaseStorage.DefaultInstance;
storageReference = storage.GetReferenceFromUrl("gs://xxx.appspot.com");
StorageReference image = storageReference.Child("image.png");
GetRemoteTexture(image);
}
private void GetRemoteTexture(StorageReference reference)
{
const long maxAllowedSize = 5 * 1024 * 1024;
reference.GetBytesAsync(maxAllowedSize).ContinueWithOnMainThread(task => {
if (task.IsFaulted || task.IsCanceled) {
Debug.LogException(task.Exception);
}
else {
byte[] fileContents = task.Result;
Debug.Log("Finished downloading! " + task.Result);
tex.LoadImage(fileContents);
rawImage.texture = tex;
}
});
}
}
I want to load this particular image from the above code but it doesn't seem to work.
I have already referenced the rawImage variable but it doesn't seem to get the texture.
And this is what I'm getting in the Console
Help is appreciated :)
Related
I am trying to get data from Firebase's Realtime database. In my database, I have a node named users. Under that, I have the UUID of All users. I want to get all UUIDs. I tried with unity Restclient API. And the result was an empty thing.
my code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using Models;
using Proyecto26;
using UnityEngine.Networking;
public class AdminPanel : MonoBehaviour
{
public GameObject manager;
public string idToken,localId;
public string databaseURL = "https://xxx.firebaseio.com/";
private void LogMessage(string title, string message) {
#if UNITY_EDITOR
EditorUtility.DisplayDialog (title, message, "Ok");
#else
Debug.Log(message);
#endif
}
void Start()
{
idToken = manager.GetComponent<SignUpData>()._idToken;
localId = manager.GetComponent<SignUpData>()._localId;
}
public void GetData()
{
RestClient.GetArray<users>(databaseURL + "users" +".json?auth=" + idToken).Then(res => {
this.LogMessage("Users", JsonHelper.ArrayToJsonString<users>(res, true));
}).Catch(err => this.LogMessage("Error", err.Message));
}
}
I'm trying to reproduce a stream audio in my unity app with a button in his onclick, i've already tried with some methods i found but it doesn't end the download... I post my class above:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class Audio_player : MonoBehaviour
{
AudioSource audioSource;
AudioClip myClip;
void Start()
{
audioSource = GetComponent<AudioSource>();
StartCoroutine(GetAudioClip());
Debug.Log("Starting to download the audio...");
}
IEnumerator GetAudioClip()
{
using (UnityWebRequest www =
UnityWebRequestMultimedia.GetAudioClip("url-sample",
AudioType.UNKNOWN))
{
yield return www.SendWebRequest();
if (www.isNetworkError)
{
Debug.Log(www.error);
}
else
{
myClip = DownloadHandlerAudioClip.GetContent(www);
audioSource.clip = myClip;
audioSource.Play();
Debug.Log("Audio is playing.");
}
}
}
public void pauseAudio(){
audioSource.Pause();
}
public void playAudio(){
audioSource.Play();
}
public void stopAudio(){
audioSource.Stop();
}
}
The console just pop up 2 messages after this onclick():
-[Adaptive Performance] No Provider was configured for use. Make sure you added at least one Provider in the Adaptive Performance Settings.
0x00007ff68171b5cd (Unity) StackWalker::GetCurrentCallstack
-Starting to download the audio...
0x00007ff68171b5cd (Unity) StackWalker::GetCurrentCallstack
I am trying to access to m_CameraDistance of the CinemachineVirtualCamera, but I get the error "NullReferenceException: Object reference not set to an instance of an object" on the last line of the code.
This is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cinemachine;
public class CameraDistanceController : MonoBehaviour
{
public float _areaCameraDistance = 10;
private float _defaultAreaCameraDistance = 8;
public CinemachineVirtualCamera _vcam;
private CinemachineFramingTransposer _framingTransposer;
void Start()
{
_framingTransposer = _vcam.GetCinemachineComponent<CinemachineFramingTransposer>();
_defaultAreaCameraDistance = _framingTransposer.m_CameraDistance;
}
}
Any ideas? I found another person with the same issue, but there is no answer:
https://quabr.com/69938009/unity3d-cinemachine-how-to-access-camera-distance-in-virtual-camera
Thanks a lot.
I am using _3rdPersonFollow, not CinemachineFramingTransposer. That is why.
See the fix below:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cinemachine;
public class CameraDistanceController : MonoBehaviour
{
public float _areaCameraDistance = 10;
private float _defaultAreaCameraDistance = 8;
public CinemachineVirtualCamera _vcam;
private Cinemachine3rdPersonFollow _3rdPersonFollow;
void Start()
{
_3rdPersonFollow = _vcam.GetCinemachineComponent<Cinemachine3rdPersonFollow>();
_defaultAreaCameraDistance = _3rdPersonFollow.CameraDistance;
}
}
I've been trying to implement a savegame function into my game. When I load the game from the save, it doesn't load the position of the player.
I have 2 main scenes: The scene in which the game is taking place, and the main menu scene. The main menu makes use of my load function, which is supposed to read my save file and put the player at a given position, however, it just loads the scene at the default position. No errors are thrown, no warning messages. Here is all of my code:
This is my Save game system:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public static class SaveSystem
{
public static void SavePlayer (Player player)
{
BinaryFormatter formatter = new BinaryFormatter();
string path = Application.persistentDataPath + "player.fun";
FileStream stream = new FileStream(path, FileMode.Create);
PlayerData data = new PlayerData(player);
formatter.Serialize(stream, data);
stream.Close();
}
public static PlayerData LoadPlayer ()
{
string path = Application.persistentDataPath + "/player.fun";
if (File.Exists(path))
{
BinaryFormatter formatter = new BinaryFormatter();
FileStream stream = new FileStream(path, FileMode.Open);
PlayerData data = formatter.Deserialize(stream) as PlayerData;
stream.Close();
return data;
}
else
{
Debug.LogError("Save file not in " + path);
return null;
}
}
}
Container for player data:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class PlayerData
{
public int level;
public int health;
public float[] position;
public int stamina;
public PlayerData (Player player)
{
level = player.level;
health = player.health;
stamina = player.stamina;
position = new float[3];
position[0] = player.transform.position.x;
position[1] = player.transform.position.y;
position[2] = player.transform.position.z;
}
}
My Scene Changing Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class SceneChanger : MonoBehaviour
{
public static bool Isload = false;
public void gotoWelwardLoad()
{
SceneManager.LoadScene("Welward");
bool Isload = true;
}
public void gotoWelward()
{
SceneManager.LoadScene("Welward");
}
public void gotomainmenu()
{
SceneManager.LoadScene("Menu");
}
}
My Player Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Player : MonoBehaviour
{
public int health = 1;
public int stamina = 1;
public int level = 1;
public void SavePlayer ()
{
SaveSystem.SavePlayer(this);
}
public void LoadPlayer ()
{
SceneManager.LoadScene("Welward");
PlayerData data = SaveSystem.LoadPlayer();
level = data.level;
health = data.health;
stamina = data.stamina;
Vector3 position;
position.x = data.position[0];
position.y = data.position[1];
position.z = data.position[2];
transform.position = position;
}
public static void gotomenu ()
{
SceneManager.LoadScene("Menu");
}
public static void Welward()
{
SceneManager.LoadScene("Welward");
SaveSystem.LoadPlayer();
}
}
Link with full unity project files:
https://drive.google.com/open?id=1mFH5aNklC0qMWeJjMT4KD0CbTTx65VRp
As BugFinder correctly points out, your save path is different than your loading path.
Try changing Application.persistentDataPath + "player.fun"; to Application.persistentDataPath + "/player.fun"; to match your loading code. Or you could move that string path variable up into the class as a const then reference it since it will be guaranteed to match.
After that however you will also need to call Player.LoadPlayer() somewhere since in your existing project you do not do that anywhere I can find, and when you call it currently it will reload the scene (which probably isn't the behaviour you want either). I would remove SceneManager.LoadScene("Welward"); from that method.
using UnityEngine;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public static class SaveSystem
{
// This is a way to make sure your path is the same, and not about to get overwritten
public static string Path => Application.persistentDataPath + "/player.fun";
public static void SavePlayer (Player player)
{
BinaryFormatter formatter = new BinaryFormatter();
FileStream stream = new FileStream(Path, FileMode.Create);
PlayerData data = new PlayerData(player);
formatter.Serialize(stream, data);
stream.Close();
// It's helpful to print out where this is going
Debug.Log($"Wrote to {Path}");
}
public static PlayerData LoadPlayer ()
{
if (File.Exists(Path))
{
BinaryFormatter formatter = new BinaryFormatter();
FileStream stream = new FileStream(Path, FileMode.Open);
PlayerData data = formatter.Deserialize(stream) as PlayerData;
stream.Close();
// It's also helpful to print out that it worked, not just log errors if it fails
Debug.Log($"Successfully read from {Path}");
return data;
}
else
{
Debug.LogError("Save file not in " + Path);
return null;
}
}
}
One thing thats noticeable is in save you use Application.persistentDataPath + "player.fun"; and in load you use, Application.persistentDataPath + "/player.fun"; So, perhaps therefore it doesnt find the file to load it. As you thought. Personally Path.Combine is a good option, platform non specific etc. So try replacing both with Path.Combine(Application.persistentDataPath,"player.fun");
From the code you provided I don't see the part where you call Player.LoadPlayer(). So add it to Player:
void Start(){
LoadPlayer();
}
Hope it helps.
As I mentioned, I tried deleting save files and runging game on a computer and it works perfectly. But on Android it either doesn't create a file, or it does create it but doesn't write anything in it.
Here is my code for SaveFileManagement:
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI;
public class onAppStart : MonoBehaviour {
public Text moneyText;
void Start () {
if (!File.Exists("doubleMoney.txt"))
{
File.Create("doubleMoney").Dispose();
System.IO.File.WriteAllText("doubleMoney.txt", "0");
}
if (!File.Exists("money.txt"))
{
File.Create("money").Dispose();
System.IO.File.WriteAllText("money.txt", "2.5");
double doubleMoney = Convert.ToDouble(System.IO.File.ReadAllText("money.txt"));
float money = ToSingle(doubleMoney);
moneyText.text = money.ToString() + "$";
}
else
{
double doubleMoney = Convert.ToDouble(System.IO.File.ReadAllText("money.txt"));
float money = ToSingle(doubleMoney);
moneyText.text = money.ToString() + "$";
}
}
public static float ToSingle(double value)
{
return (float)value;
}
}
You're trying to create "doubleMoney", but write to/check existence of "doubleMoney.txt". Fix your filenames to be consistent.