我正在嘗試從我的GameController.cs腳本訪(fǎng)問(wèn)協(xié)程,協(xié)程位于我的DatabaseManager.cs腳本中。我正在嘗試像這樣訪(fǎng)問(wèn)協(xié)程: DatabaseManager d1 = new DatabaseManager(); d1.uploadData();這給了我一個(gè)空引用異常。我知道在我嘗試訪(fǎng)問(wèn)的協(xié)程中一切正常,因?yàn)檫@些腳本與我制作的另一個(gè)項(xiàng)目完全相同,唯一的區(qū)別是在另一個(gè)項(xiàng)目中我通過(guò)一個(gè)運(yùn)行良好的動(dòng)畫(huà)事件調(diào)用協(xié)程,但是試圖通過(guò)這個(gè)項(xiàng)目中的代碼調(diào)用它給了我這個(gè)問(wèn)題。數(shù)據(jù)庫(kù)管理器腳本附加到 Player 游戲?qū)ο髷?shù)據(jù)庫(kù)管理器腳本using UnityEngine;using UnityEngine.Networking;using System.Collections;using UnityEngine.UI;using CompanionLibrary; //include my library to utilise its functions//use neccessary libraries. //This class handles sending game data to the database. public class DatabaseManager : MonoBehaviour { //declare variables to hold data values. static string username; string password; int score =0; int kills=0; //initialise variables to 0 int bulletsFired=0; int bulletsHit=0; int bulletsMissed=0; int timePlayed = 0; int scorePerMin=0; StatGeneration companion = new StatGeneration(); //On awake function to check if sign in or logged in booleans are set. public void Awake() { if (ButtonManagers.signedUp == true) //if signedUp boolean is true.... { username = ButtonManagers.signUpUsername; //assign the username to equal the signUpUsername value. password = ButtonManagers.signUpPassword; //assign the password to equal the signUpPassword value. Debug.Log("Username: " + username); Debug.Log("Password: " + password); } //if loggedIn boolean is true.... if (ButtonManagers.loggedIn == true) { username = ButtonManagers.loginUsername;//assign the username to equal the loggedInUsername value. password = ButtonManagers.loginPassword;//assign the password to equal the loggedInPassword value. } }
1 回答

阿波羅的戰(zhàn)車(chē)
TA貢獻(xiàn)1862條經(jīng)驗(yàn) 獲得超6個(gè)贊
如果DatabaseManager
是一個(gè)單一行為,那么你不應(yīng)該用new
關(guān)鍵字來(lái)實(shí)例化它。正確方法:
AddComponent<DatabaseManager>();
如果使用 new 關(guān)鍵字創(chuàng)建 MonoBehaviour,則調(diào)用將在運(yùn)行時(shí)失敗。這是因?yàn)?MonoBehaviour 是一個(gè)組件,并且需要附加到 GameObject,這是人們討厭統(tǒng)一序列化的原因之一,因?yàn)槟枰粋€(gè)容器類(lèi)來(lái)存儲(chǔ) monobehaviour 字段和屬性
如何使用:
DatabaseManager databaseManager = gameObject.AddComponent<DatabaseManager>();
如果您不在執(zhí)行此操作的游戲?qū)ο笊?,并且您不在單一行為?/p>
var tempgameObject = new GameObject(); DatabaseManager databaseManager = tempgameObject.AddComponent<DatabaseManager>();
- 1 回答
- 0 關(guān)注
- 91 瀏覽
添加回答
舉報(bào)
0/150
提交
取消