C#:尝试使用Watson Assistant V2创建会话时,IBM-Watson Unity SDK NullReferenceException

时间:2019-01-27 09:41:49

标签: c# unity3d nullreferenceexception ibm-watson

我试图在IBM Watson Unity SDK中运行该示例,但是当它尝试创建会话时却遇到了NullReferenceException。

这是SDK的示例脚本,但修改后的行除外。我添加这些是因为出于某些奇怪的原因,未将用户名和密码添加到凭据中。如果您对此有一个答案,那么我会为此问题here

创建一个单独的问题
using System.Collections;
using System.Collections.Generic;
using IBM.Watson.DeveloperCloud.Connection;
using IBM.Watson.DeveloperCloud.Logging;
using IBM.Watson.DeveloperCloud.Utilities;
using IBM.WatsonDeveloperCloud.Assistant.v2;
using UnityEngine;

namespace IBM.Watson.DeveloperCloud.Services.Assistant.v2
{
    public class ExampleAssistantV2 : MonoBehaviour
    {
        #region PLEASE SET THESE VARIABLES IN THE INSPECTOR
        [Space(10)]
        [Tooltip("The service URL (optional). This defaults to \"https://gateway.watsonplatform.net/assistant/api\"")]
        [SerializeField]
        private string _serviceUrl;
        [Tooltip("The assistantId to run the example.")]
        [SerializeField]
        private string _assistantId;
        [Tooltip("The version date with which you would like to use the service in the form YYYY-MM-DD.")]
        [SerializeField]
        private string _versionDate;
        [Header("CF Authentication")]
        [Tooltip("The authentication username.")]
        [SerializeField]
        private string _username;
        [Tooltip("The authentication password.")]
        [SerializeField]
        private string _password;
        [Header("IAM Authentication")]
        [Tooltip("The IAM apikey.")]
        [SerializeField]
        private string _iamApikey;
        [Tooltip("The IAM url used to authenticate the apikey (optional). This defaults to \"https://iam.bluemix.net/identity/token\".")]
        [SerializeField]
        private string _iamUrl;
        #endregion

        private Assistant _service;

        private bool _createSessionTested = false;
        private bool _messageTested = false;
        private bool _deleteSessionTested = false;
        private string _sessionId;

        private void Start()
        {
            LogSystem.InstallDefaultReactors();
            Runnable.Run(CreateService());
        }

        private IEnumerator CreateService()
        {
            //  Create credential and instantiate service
            Credentials credentials = null;
            if (!string.IsNullOrEmpty(_username) && !string.IsNullOrEmpty(_password))
            {
                //  Authenticate using username and password
                credentials = new Credentials(_username, _password, _serviceUrl);
                credentials.Username = _username; //Modified
                credentials.Password = _password; //Modified
                credentials.Url = _serviceUrl; //Modified
            }
            else if (!string.IsNullOrEmpty(_iamApikey))
            {
                //  Authenticate using iamApikey
                TokenOptions tokenOptions = new TokenOptions()
                {
                    IamApiKey = _iamApikey,
                    IamUrl = _iamUrl
                };

                credentials = new Credentials(tokenOptions, _serviceUrl);

                //  Wait for tokendata
                while (!credentials.HasIamTokenData())
                    yield return null;
            }
            else
            {
                throw new WatsonException("Please provide either username and password or IAM apikey to authenticate the service.");
            }

            _service = new Assistant(credentials);
            _service.VersionDate = _versionDate;

            Runnable.Run(Examples());
        }

        private IEnumerator Examples()
        {
            Log.Debug("ExampleAssistantV2.Examples()", "Attempting to CreateSession");
            _service.CreateSession(OnCreateSession, OnFail, _assistantId);

            while (!_createSessionTested)
            {
                yield return null;
            }

            Log.Debug("ExampleAssistantV2.Examples()", "Attempting to Message");
            _service.Message(OnMessage, OnFail, _assistantId, _sessionId);

            while (!_messageTested)
            {
                yield return null;
            }

            Log.Debug("ExampleAssistantV2.Examples()", "Attempting to DeleteSession");
            _service.DeleteSession(OnDeleteSession, OnFail, _assistantId, _sessionId);

            while (!_deleteSessionTested)
            {
                yield return null;
            }

            Log.Debug("ExampleAssistantV2.Examples()", "Assistant examples complete.");
        }

        private void OnDeleteSession(object response, Dictionary<string, object> customData)
        {
            Log.Debug("ExampleAssistantV2.OnDeleteSession()", "Session deleted.");
            _createSessionTested = true;
        }

        private void OnMessage(MessageResponse response, Dictionary<string, object> customData)
        {
            _messageTested = true;
        }

        private void OnCreateSession(SessionResponse response, Dictionary<string, object> customData)
        {
            Log.Debug("ExampleAssistantV2.OnCreateSession()", "Session: {0}", response.SessionId);
            _sessionId = response.SessionId;
            _createSessionTested = true;
        }

        private void OnFail(RESTConnector.Error error, Dictionary<string, object> customData)
        {
            Log.Debug("ExampleAssistantV2.OnFail()", "Call failed: {0}: {1}", error.ErrorCode, error.ErrorMessage);
        }
    }
}

抛出的错误代码:

[01/27/2019 09:33:18][Unity][CRITICAL] Unity Exception NullReferenceException: Object reference not set to an instance of an object : IBM.Watson.DeveloperCloud.Services.Assistant.v2.ExampleAssistantV2.OnFail (IBM.Watson.DeveloperCloud.Connection.Error error, System.Collections.Generic.Dictionary`2 customData) (at Assets/Watson/Examples/ServiceExamples/Scripts/ExampleAssistantV2.cs:157)
IBM.Watson.DeveloperCloud.Services.Assistant.v2.Assistant.OnCreateSessionResponse (IBM.Watson.DeveloperCloud.Connection.Request req, IBM.Watson.DeveloperCloud.Connection.Response resp) (at Assets/Watson/Scripts/Services/Assistant/v2/Assistant.cs:208)
IBM.Watson.DeveloperCloud.Connection.RESTConnector+<ProcessRequestQueue>c__Iterator0.MoveNext () (at Assets/Watson/Scripts/Connection/RESTConnector.cs:581)
IBM.Watson.DeveloperCloud.Utilities.Runnable+Routine.MoveNext () (at Assets/Watson/Scripts/Utilities/Runnable.cs:131)
UnityEngine.SetupCoroutine.InvokeMoveNext (IEnumerator enumerator, IntPtr returnValueAddress) (at C:/buildslave/unity/build/Runtime/Export/Coroutines.cs:17)

UnityEngine.Debug:LogError(Object)
IBM.Watson.DeveloperCloud.Debug.DebugReactor:ProcessLog(LogRecord) (at Assets/Watson/Scripts/Debug/DebugReactor.cs:60)
IBM.Watson.DeveloperCloud.Logging.LogSystem:ProcessLog(LogRecord) (at Assets/Watson/Scripts/Logging/Logger.cs:206)
IBM.Watson.DeveloperCloud.Logging.Log:Critical(String, String, Object[]) (at Assets/Watson/Scripts/Logging/Logger.cs:294)
IBM.Watson.DeveloperCloud.Logging.LogSystem:UnityLogCallback(String, String, LogType) (at Assets/Watson/Scripts/Logging/Logger.cs:167)
UnityEngine.Application:CallLogCallback(String, String, LogType, Boolean)

NullReferenceException: Object reference not set to an instance of an object
IBM.Watson.DeveloperCloud.Services.Assistant.v2.ExampleAssistantV2.OnFail (IBM.Watson.DeveloperCloud.Connection.Error error, System.Collections.Generic.Dictionary`2 customData) (at Assets/Watson/Examples/ServiceExamples/Scripts/ExampleAssistantV2.cs:157)
IBM.Watson.DeveloperCloud.Services.Assistant.v2.Assistant.OnCreateSessionResponse (IBM.Watson.DeveloperCloud.Connection.Request req, IBM.Watson.DeveloperCloud.Connection.Response resp) (at Assets/Watson/Scripts/Services/Assistant/v2/Assistant.cs:208)
IBM.Watson.DeveloperCloud.Connection.RESTConnector+<ProcessRequestQueue>c__Iterator0.MoveNext () (at Assets/Watson/Scripts/Connection/RESTConnector.cs:581)
IBM.Watson.DeveloperCloud.Utilities.Runnable+Routine.MoveNext () (at Assets/Watson/Scripts/Utilities/Runnable.cs:131)
UnityEngine.SetupCoroutine.InvokeMoveNext (IEnumerator enumerator, IntPtr returnValueAddress) (at C:/buildslave/unity/build/Runtime/Export/Coroutines.cs:17)

编辑: 注意,我是在不好的时候问这个问题的,所以我决定对其进行编辑,以查看它是否更有可能得到回答。仍然没有进展,无法完全弄清什么是null。任何见识将不胜感激。

2 个答案:

答案 0 :(得分:0)

Unity资产存储上的

SDK已过时。不得不切换到Github上的那个。进行更新后,我不再收到错误。但是,在某些情况下,即使您稍微修改一下示例,就有机会收到NullReferenceException。

答案 1 :(得分:0)

该错误是由于不提供AssistantId导致的Assistant V2。较旧的版本没有对AssistantId进行空检查。来自github的最新版本应具有null检查。