启动协程统一给出空引用异常

我正在尝试从我的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.

            }

        }



慕后森
浏览 80回答 1
1回答

阿波罗的战车

如果DatabaseManager是一个单一行为,那么你不应该用new关键字来实例化它。正确方法:AddComponent<DatabaseManager>();如果使用 new 关键字创建 MonoBehaviour,则调用将在运行时失败。这是因为 MonoBehaviour 是一个组件,并且需要附加到 GameObject,这是人们讨厌统一序列化的原因之一,因为您需要一个容器类来存储 monobehaviour 字段和属性如何使用:DatabaseManager&nbsp;databaseManager&nbsp;=&nbsp;gameObject.AddComponent<DatabaseManager>();如果您不在执行此操作的游戏对象上,并且您不在单一行为中var&nbsp;tempgameObject&nbsp;=&nbsp;new&nbsp;GameObject(); DatabaseManager&nbsp;databaseManager&nbsp;=&nbsp;tempgameObject.AddComponent<DatabaseManager>();
打开App,查看更多内容
随时随地看视频慕课网APP