Hello!
Is there a way to check the type-casting result of an input object is valid/invalid?
Such as, “If the collider of OnCollisionEnter is BoxCollider, then do something”.
I know that there maybe other ways to achieve the same result of the above example, but in real use I’m passing my custom classes to the graph, and hope for a way to do an if/switch process to control the behavior.
I’ve already created a node by using SerializableType and seems to be working, but I’m not sure if it is the correct way to do it. Visual Scripting is hiding the SerializableType Deserializing part to be an internal editor feature (-> SerializableTypeExtensions), so I’m not sure if that means I shouldn’t be checking the type during runtime.
Just for someone curios, below is my code and the result node:
using System;
using Unity.VisualScripting;
using UnityEngine.Scripting;
[Preserve]
public class TypeCastNode : Unit
{
[Serialize, Inspectable, UnitHeaderInspectable]
public SerializableType serializableCastType;
private Type castType;
[DoNotSerialize]
public ControlInput inputTrigger;
[DoNotSerialize]
public ValueInput inputObject;
[DoNotSerialize]
[PortLabel("IsNotNull")]
public ControlOutput isNotNullOutputTrigger;
[DoNotSerialize]
[PortLabel("IsNull")]
public ControlOutput isNullOutputTrigger;
[DoNotSerialize]
public ValueOutput outputCastResultObject;
protected override void Definition()
{
inputTrigger = ControlInput("input", CheckCastResult);
isNotNullOutputTrigger = ControlOutput("IsNotNull");
isNullOutputTrigger = ControlOutput("IsNull");
inputObject = ValueInput<object>("object");
DeserializeType();
if (castType != null) {
outputCastResultObject = ValueOutput(castType, "cast result", (flow) => flow.GetValue(inputObject));
}
}
private void DeserializeType()
{
castType = Type.GetType(serializableCastType.Identification);
}
private ControlOutput CheckCastResult(Flow flow)
{
var obj = flow.GetValue(inputObject);
var objType = obj?.GetType();
if (castType != null && objType != null && castType.IsAssignableFrom(objType)) {
return isNotNullOutputTrigger;
}
return isNullOutputTrigger;
}
}
