亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

啟動協程統一給出空引用異常

啟動協程統一給出空引用異常

C#
慕后森 2022-10-23 13:47:18
我正在嘗試從我的GameController.cs腳本訪問協程,協程位于我的DatabaseManager.cs腳本中。我正在嘗試像這樣訪問協程: DatabaseManager d1 = new DatabaseManager(); d1.uploadData();這給了我一個空引用異常。我知道在我嘗試訪問的協程中一切正常,因為這些腳本與我制作的另一個項目完全相同,唯一的區別是在另一個項目中我通過一個運行良好的動畫事件調用協程,但是試圖通過這個項目中的代碼調用它給了我這個問題。數據庫管理器腳本附加到 Player 游戲對象數據庫管理器腳本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 回答

?
阿波羅的戰車

TA貢獻1862條經驗 獲得超6個贊

如果DatabaseManager是一個單一行為,那么你不應該用new關鍵字來實例化它。正確方法:

AddComponent<DatabaseManager>();

如果使用 new 關鍵字創建 MonoBehaviour,則調用將在運行時失敗。這是因為 MonoBehaviour 是一個組件,并且需要附加到 GameObject,這是人們討厭統一序列化的原因之一,因為您需要一個容器類來存儲 monobehaviour 字段和屬性

如何使用:

DatabaseManager databaseManager = gameObject.AddComponent<DatabaseManager>();

如果您不在執行此操作的游戲對象上,并且您不在單一行為中

var tempgameObject = new GameObject();
DatabaseManager databaseManager = tempgameObject.AddComponent<DatabaseManager>();


查看完整回答
反對 回復 2022-10-23
  • 1 回答
  • 0 關注
  • 87 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號