Index was outside the bounds of the array. Login+<LoginPlayer>d__4.MoveNext () (at Assets/Login.cs:29) - c#

I'm building a system in Unity that takes a register and login menu connected to a MySQL database through PHPMyAdmin, has users log in, then allows them to choose between playing two games. I've been getting this error since I linked the games and I can't figure out how to fix it. The register works fine, but it won't allow for log in.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class Login : MonoBehaviour
{
public TMP_InputField nameField;
public TMP_InputField passwordField;
public Button submitButton;
public void CallLogin()
{
StartCoroutine(LoginPlayer());
}
IEnumerator LoginPlayer()
{
WWWForm form = new WWWForm();
form.AddField("name", nameField.text);
form.AddField("password", passwordField.text);
WWW www = new WWW("http://localhost/sqlconnect/login.php", form);
yield return www;
if (www.text[0] == '0')
{
dbmanager.username = nameField.text;
dbmanager.score = int.Parse(www.text.Split('\t')[1]);
UnityEngine.SceneManagement.SceneManager.LoadScene(0);
}
else
{
Debug.Log("User Login failed. Error #" + www.text);
}
}
public void VerifyInputs()
{
submitButton.interactable = (nameField.text.Length >= 8 && passwordField.text.Length >= 8);
}
}
I've been trying to figure out what happened for hours and need some extra insight, can anyone please help?

Related

Why doesn't Google Play Game authorization work in Unity?

I did everything right, I specified SHA1 in the Google API, Linked it all to Google Console, inserted resources and Web Client ID into Unity, but every time I try to log in, it writes "Canceled".
In LogCat I don't get errors, there are only:
*** [Play Games Plugin 0.11.01] 02.18.23 ERROR: Returning an error code
GooglePlayGames.OurUtils.PlayGamesHelperObject:Update()
Google Play services out of date for iae.perfectray.dogs. Reqires 21300000 but found 212621032
Here is the authorization code:
using GooglePlayGames;
using GooglePlayGames.BasicApi;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Auth : MonoBehaviour
{
// Start is called before the first frame update
public Text text;
void Start()
{
PlayGamesPlatform.Activate();
PlayGamesPlatform.DebugLogEnabled = true;
}
public void Authh()
{
PlayGamesPlatform.Instance.Authenticate(ProccessAuth);
}
internal void ProccessAuth(SignInStatus status)
{
if(status == SignInStatus.Success)
{
text.text = "Status: Succesfull";
}
else
{
text.text = "Status: " + status;
}
}
I've already tried everything, nothing works(

My unity login with Firebase is not working

My register user is working perfectly, however when i try to log a user in i do not get any kind of message, successful login or failed login. I am trying to log my user in then move to my logged in screen. If anyone is able to see what it is i am doing wrong i would be very thankful!
I will provided my code below.
Thank you for your help!
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System;
using System.Text.RegularExpressions;
using UnityEngine.SceneManagement;
using Firebase;
using Firebase.Auth;
public class Login : MonoBehaviour {
public GameObject email;
public GameObject password;
private string Email;
private string Password;
Firebase.Auth.FirebaseAuth auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
void Update () {
if (email.GetComponent<InputField>().isFocused){
password.GetComponent<InputField>().Select();
}
if (Password != ""&&Password != ""){
LoginButton();
}
Email = email.GetComponent<InputField>().text;
Password = password.GetComponent<InputField>().text;
}
public void LoginButton()
{
auth.SignInWithEmailAndPasswordAsync(Email, Password).ContinueWith(task => {
if (task.IsCanceled) {
Debug.LogError("SignInWithEmailAndPasswordAsync was canceled.");
return;
}
if (task.IsFaulted) {
Debug.LogError("SignInWithEmailAndPasswordAsync encountered an error: " + task.Exception);
return;
}
Firebase.Auth.FirebaseUser newUser = task.Result;
Debug.LogFormat("User signed in successfully: {0} ({1})",
newUser.DisplayName, newUser.UserId);
SceneManager.LoadScene("LoginScreen");
});
}
}
Replace ContinueWith with ContinueWithOnMainThread, I think you should be good. If not, make sure you've enabled email sign in in the Firebase console.
I suspect that everything's working as expected, but because you're using ContinueWith your SceneManager logic is happening off of the main thread. In the best case scenario, this just won't work. In the worst case, you might see a crash.
See my article on threading in Unity and my video on Authentication for more information.

Writing .txt file in android

I need help with a problem in our system. We are using unity and visual studio C# to create a mobile VR game using gaze controls only (no controller). We need to find a way to write debug logs into a text file and save to android internal storage. Thanks in advance for the help!!
That is our code below
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using UnityEngine;
public class VRPlace : MonoBehaviour
{
...
void OnTriggerEnter(Collider other)
{
string path = "Assets/Resources/PlacesLog.txt";
StreamWriter testing = new StreamWriter(path, true);
if (other.gameObject.name == "Hospital")
{
GameObject otherObj = other.gameObject;
Debug.Log("Triggered to: " + otherObj);
}
testing.WriteLine(other.gameObject.name);
testing.Close();
}
}
here is a sample for saving a .txt file with StreamWriter.
class FileSaver
{
static void Main()
{
// Create a StreamWriter instance
StreamWriter writer = new
StreamWriter(Application.PersistentDataPath + "/droidlog.txt");
// This using statement will ensure the writer will be closed when no longer used
using(writer)
{
// Loop through the numbers from 1 to 20 and write them
for (int i = 1; i <= 20; i++)
{
writer.WriteLine(i);
}
}
}
}
this saves the numbers 1-20, you will want to fill in the blanks... good luck!

QR Code Scanner in Unity?

I am trying to get QRCode reader in unity that works on ios and Android.
Unity Zxing QR code scanner integration
Using above answer I Have added Vuforia (Working perfectly alone). then i also have added Zxing.unity.dll in plugins folder, then added this script to ARCamera in a scene.
using UnityEngine;
using System;
using System.Collections;
using Vuforia;
using System.Threading;
using ZXing;
using ZXing.QrCode;
using ZXing.Common;
[AddComponentMenu("System/VuforiaScanner")]
public class VuforiaScanner : MonoBehaviour
{
private bool cameraInitialized;
private BarcodeReader barCodeReader;
void Start()
{
barCodeReader = new BarcodeReader();
StartCoroutine(InitializeCamera());
}
private IEnumerator InitializeCamera()
{
// Waiting a little seem to avoid the Vuforia's crashes.
yield return new WaitForSeconds(1.25f);
var isFrameFormatSet = CameraDevice.Instance.SetFrameFormat(Image.PIXEL_FORMAT.RGB888, true);
Debug.Log(String.Format("FormatSet : {0}", isFrameFormatSet));
// Force autofocus.
var isAutoFocus = CameraDevice.Instance.SetFocusMode(CameraDevice.FocusMode.FOCUS_MODE_CONTINUOUSAUTO);
if (!isAutoFocus)
{
CameraDevice.Instance.SetFocusMode(CameraDevice.FocusMode.FOCUS_MODE_NORMAL);
}
Debug.Log(String.Format("AutoFocus : {0}", isAutoFocus));
cameraInitialized = true;
}
private void Update()
{
if (cameraInitialized)
{
try
{
var cameraFeed = CameraDevice.Instance.GetCameraImage(Image.PIXEL_FORMAT.RGB888);
if (cameraFeed == null)
{
return;
}
var data = barCodeReader.Decode(cameraFeed.Pixels, cameraFeed.BufferWidth, cameraFeed.BufferHeight, RGBLuminanceSource.BitmapFormat.RGB24);
if (data != null)
{
// QRCode detected.
Debug.Log(data.Text);
}
else
{
Debug.Log("No QR code detected !");
}
}
catch (Exception e)
{
Debug.LogError(e.Message);
}
}
}
}
But it is still not detecting any QRCode. Is there any other way to do QRcode reading and writing except Zxing? or any working sample project you have?
I also tried to implement a QRCode Reader with Vuforia and XZing using almost the same code you used. For me it worked, but it took very very long to detect the QRCode.
When I used a Color32 array instead of cameraFeed.pixels it was much quicker:
GUI.DrawTexture(screenRect, webCamTexture, ScaleMode.ScaleToFit);
try
{
IBarcodeReader barcodeReader = new BarcodeReader();
var result = barcodeReader.Decode(webCamTexture.GetPixels32(),
webCamTexture.width, webCamTexture.height);
if (result != null)
{
Debug.Log("DECODED TEXT FROM QR: " + result.Text);
loadNewPoi(Convert.ToInt32(result.Text));
PlayerPrefs.SetInt("camera_enabled", Convert.ToInt32(false));
webCamTexture.Stop();
}
}
But in this example I was using a WebCamTexture instead of Vuforia.
Unluckily it isn't possible to get a Color32 array with GetPixels32() from the Vuforia camera.
Another option is to use the QRCodes as Image-Targets, but I have a lot of wrong detections doing this.
For me there is no fitting solution for XZing together with Vuforia at the moment.

Load file downloaded iOS app created in Unity

I'm trying to load a json file downloaded and saved in the persistentDataPath of an iOS device. The download and save works great. However I think I have big issues to load the file. In fact when I try to compile the project in Xcode I have some errors messages.
First here is my C# code :
using UnityEngine;
using System.Collections;
using System.IO;
using System.Net;
using UnityEngine.UI;
public class ReadJson : MonoBehaviour
{
public Text City;
public Text Temperature;
public Image Weather;
public Text WeatherUrl;
[System.Serializable]
public class CityInfo
{
public string name;
}
[System.Serializable]
public class CurrentCondition
{
public string date;
public string hour;
public int tmp;
public int wnd_spd;
public int wnd_gust;
public string wnd_dir;
public double pressure;
public int humidity;
public string condition;
public string icon;
public string icon_big;
}
[System.Serializable]
public class RootObject
{
public CityInfo city_info;
public CurrentCondition current_condition;
}
void Start () {
WebClient client = new WebClient();
File.Delete(Path.Combine (Application.persistentDataPath, "myjson.json"));
client.DownloadFile ("http://www.myjsonurl", Path.Combine (Application.persistentDataPath, "myjson.json"));
TextAsset asset = Resources.Load (Path.Combine (Application.dataPath + "/Documents", "myjson")) as TextAsset;
RootObject m = JsonUtility.FromJson<RootObject> (asset.text);
City.text = m.city_info.name;
Temperature.text = (m.current_condition.tmp).ToString();
}
}
And now the xcode console :
2016-10-21 17:01:20.766001 json[1404:516674] [DYMTLInitPlatform] platform initialization successful
2016-10-21 17:01:20.929950 json[1404:516508] -> registered mono modules 0xb95f70
2016-10-21 17:01:21.356590 json[1404:516508] You've implemented -[<UIApplicationDelegate> application:didReceiveRemoteNotification:fetchCompletionHandler:], but you still need to add "remote-notification" to the list of your supported UIBackgroundModes in your Info.plist.
-> applicationDidFinishLaunching()
2016-10-21 17:01:21.452967 json[1404:516508] Metal GPU Frame Capture Enabled
2016-10-21 17:01:21.453369 json[1404:516508] Metal API Validation Enabled
-> applicationDidBecomeActive()
Init: screen size 750x1334
Initializing Metal device caps
Initialize engine version: 5.3.4f1 (fdbb5133b820)
UnloadTime: 1.705875 ms
Salut/var/mobile/Containers/Data/Application/51A2490E-94EB-4904-9F2E-112AD5632A98/Documents
(Filename: /Users/builduser/buildslave/unity/build/artifacts/generated/common/runtime/UnityEngineDebugBindings.gen.cpp Line: 37)
NullReferenceException: A null value was found where an object instance was required.
(Filename: currently not available on il2cpp Line: -1)
Setting up 1 worker threads for Enlighten.
Thread -> id: 19f17000 -> priority: 1
If someone has an idea. Thanks a lot in advance.
The problem with your code is on this line:
TextAsset asset = Resources.Load(Path.Combine(Application.dataPath + "/Documents", "myjson")) as TextAsset;
I don't think you understand how and when to use Resources.Load. If you want to use the Resources.Load function, you must create a special folder from the Editor. This folder should be at <ProjectDirectory>/Assets/Resources. You can only put/write stuff into this folder from the Editor. You can't do it after build on iOS. It becomes read only after you build it. This special folder can then be read with the Resources.Load function.
Replacing:
TextAsset asset = Resources.Load(Path.Combine(Application.dataPath + "/Documents", "myjson")) as TextAsset;
with
string text = File.ReadAllText(Path.Combine(Application.persistentDataPath, "myjson.json"));
RootObject m = JsonUtility.FromJson<RootObject>(text);
City.text = m.city_info.name;
Temperature.text = (m.current_condition.tmp).ToString();
Should solve your problem.
Another API that should not be using is WebClient. Unless you have a good reason to use that, you shouldn't. You should either use the WWW or UnityWebRequest(newer and recommended) API.
This is what your code should look like without WebClient:
void Start()
{
StartCoroutine(DownloadAndloadJson());
}
IEnumerator DownloadAndloadJson()
{
string url = "http://www.myjsonurl";
UnityWebRequest www = UnityWebRequest.Get(url);
yield return www.Send();
if (www.isError)
{
Debug.Log(www.error);
}
else
{
//Sucessfully downloaded the Json File
Debug.Log("Json: " + www.downloadHandler.text);
string jsonFile = www.downloadHandler.text;
//Delete old json file. Don't know why but this was in your original code
File.Delete(Path.Combine(Application.persistentDataPath, "myjson.json"));
//Save the downloaded data as File
File.WriteAllText(Path.Combine(Application.persistentDataPath, "myjson.json"), jsonFile);
//Load the downloaded data
string text = File.ReadAllText(Path.Combine(Application.persistentDataPath, "myjson.json"));
Debug.Log(text);
RootObject m = JsonUtility.FromJson<RootObject>(text);
City.text = m.city_info.name;
Temperature.text = (m.current_condition.tmp).ToString();
}
}
If you have problems please update to Unity 5.4. The UnityWebRequest API should be used for this and it was introduced in 5.3 but bugs were fixed in 5.4. You need using UnityEngine.Networking; to use UnityWebRequest.

Categories

Resources