In the dialogue system, I keep getting his error when creating a new dialogue scriptable object:
[Worker0] NullReferenceException: Object reference not set to an instance of an object
Dialogue.OnValidate () (at Assets/Scripts/Dialogue/Dialogue.cs:26)
Dialogue.Awake () (at Assets/Scripts/Dialogue/Dialogue.cs:18)
I’m not sure how to fix it
Here is my code:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
[CreateAssetMenu(fileName = "New Dialogue", menuName = "Dialogue/New Dialogue", order = 0)]
public class Dialogue : ScriptableObject, ISerializationCallbackReceiver
{
[SerializeField] List<DialogueNode> nodesList = new List<DialogueNode>();
Dictionary<string, DialogueNode> nodeLookUp = new Dictionary<string, DialogueNode>();
void Awake()
{
OnValidate();
}
private void OnValidate()
{
nodeLookUp.Clear();
foreach (DialogueNode node in GetAllNodes())
{
nodeLookUp[node.name] = node;
}
}
public IEnumerable<DialogueNode> GetAllNodes()
{
return nodesList;
}
public DialogueNode GetRootNode()
{
return nodesList[0];
}
public IEnumerable<DialogueNode> GetAllChildren(DialogueNode parentNode)
{
foreach (string childID in parentNode.Children)
{
if (nodeLookUp.ContainsKey(childID))
yield return nodeLookUp[childID];
}
}
#if UNITY_EDITOR
public void CreateNode(DialogueNode parent)
{
DialogueNode newNode = MakeNode(parent);
Undo.RegisterCreatedObjectUndo(newNode, "created dialogue node");
Undo.RecordObject(this, "new dialogue node");
AddNode(newNode);
}
private static DialogueNode MakeNode(DialogueNode parent)
{
Vector2 rectOffset = new Vector2(300, 0);
DialogueNode newNode = CreateInstance<DialogueNode>();
newNode.name = Guid.NewGuid().ToString();
if (parent != null)
{
parent.AddChild(newNode.name);
newNode.SetPosition(parent.Rect.position + rectOffset);
}
return newNode;
}
private void AddNode(DialogueNode newNode)
{
nodesList.Add(newNode);
OnValidate();
}
public void DeleteNode(DialogueNode nodeToDelete)
{
Undo.RecordObject(this, "deleted dialogue node");
nodesList.Remove(nodeToDelete);
OnValidate();
CleanRemainingChildren(nodeToDelete);
Undo.DestroyObjectImmediate(nodeToDelete);
}
private void CleanRemainingChildren(DialogueNode nodeToDelete)
{
foreach (DialogueNode node in GetAllNodes())
{
node.RemoveChild(nodeToDelete.name);
}
}
#endif
public void OnBeforeSerialize() //When you save a file to the HHD
{
#if UNITY_EDITOR
if (nodesList.Count == 0)
{
DialogueNode newNode = MakeNode(null);
AddNode(newNode);
}
if (AssetDatabase.GetAssetPath(this) != "")
{
foreach (DialogueNode node in GetAllNodes())
{
if (AssetDatabase.GetAssetPath(node) == "")
{
AssetDatabase.AddObjectToAsset(node, this);
}
}
}
#endif
}
public void OnAfterDeserialize() //When you load a file from the HHD
{
//Do nothing
}
}