assignment of object not converting to defined class

I am doing the
Unity Dialogue & Quests: Intermediate C# Game Coding
training and got stuck.

Code:
1 private void OnSelectionChanged()
2 {
3 Debug.Log(“Selection Made”);
4 System.Object obj = Selection.activeObject;
5 Dialogue dialogue = obj as Dialogue;
6 if (dialogue != null)
7 {
8 selectedDialogue = dialogue;
9 Repaint();
10 }
11 else{
12 Debug.Log("dialogue not set "+obj.GetType());
13 }
14
15 }
Debug output
Selection Made
UnityEngine.Debug:Log (object)
RPG.Dialogue.Editor.DialogueEditor:OnSelectionChanged () (at Assets/Dialogue/Editor/DialogueEditor.cs:58)
UnityEditor.Selection:Internal_CallSelectionChanged ()
dialogue not set Dialogue
The Dialogue class is defined as
public class Dialogue : ScriptableObject, ISerializationCallbackReceiver

So my question is why does line 5 not set the dialogue variable to the Dialogue converted object?

Please use Code Tags (see first thread in forum)

The most probable reason you are seeing your output is because Selection.activeObject returns null. How do you guard against that?

-ch

From the details supplied in the tutorial the as directive will return null if the type of the selected object is not the same type as the target that is being set.
The section that sets the selectedDialogue will trigger a function elsewhere.
I have noticed something else that maybe why this is happening.
In the Inspector the object I am selecting is shown as an empty object.
I just checked and it looks like the script being assigned as part of the object creation was not getting the correct script assigned. I clicked on the small circle with a dot in it on the line that showed in grey Script #Dialogue O and it changed the icon of the object in the assets to a script. I deleted that object and now when I create a new dialogue in the game folder all is working again.
I am not aware of doing anything to cause this but all now seems to be ok.
Thank you for responding and prompting me to look in areas I had not looked before.

Unity uses fake null objects in certain cases–values that aren’t actually null, but Unity overrides the operators == and != so that these objects “equal” null.

I suspect that “obj as Dialogue” actually successfully cast your object, but the object being cast is a fake null. Thus, its type is Dialogue, but it still == null.

The most common case for this is if the variable used to point to a real object but the object got destroyed. But there are some other cases, too; for instance, IIRC, when running in the editor (but not in a final build), GetComponent will return a fake null instead of a real null if it fails to find the component you’re looking for.

1 Like