///---------------------------------------------------------------------------------------------- ///Add a listener to several messages public void Register(object target, params string[] messages) { if (target == null) { return; } for (var i = 0; i < messages.Length; i++) { var method = target.GetType().GetMethod(messages[i], METHOD_FLAGS); if (method == null) { Logger.LogError(string.Format("Type '{0}' does not implement a method named '{1}', for the registered event to use.", target.GetType().FriendlyName(), messages[i]), "Events", target); continue; } List <object> targetObjects = null; if (!listeners.TryGetValue(messages[i], out targetObjects)) { targetObjects = new List <object>(); listeners[messages[i]] = targetObjects; } if (!targetObjects.Contains(target)) { targetObjects.Add(target); } } }
///<summary>Duplicate the connection providing a new source and target</summary> public Connection Duplicate(Node newSource, Node newTarget) { if (newSource == null || newTarget == null) { Logger.LogError("Can't Duplicate a Connection without providing NewSource and NewTarget Nodes"); return(null); } //deep clone var newConnection = JSONSerializer.Clone <Connection>(this); UndoUtility.RecordObject(newSource.graph, "Duplicate Connection"); newConnection._UID = null; newConnection.sourceNode = newSource; newConnection.targetNode = newTarget; newSource.outConnections.Add(newConnection); newTarget.inConnections.Add(newConnection); if (newSource.graph != null) { foreach (var task in Graph.GetTasksInElement(newConnection)) { task.Validate(newSource.graph); } } //-- newConnection.OnValidate(newSource.outConnections.Count - 1, newTarget.inConnections.Count - 1); UndoUtility.SetDirty(newSource.graph); return(newConnection); }
///<summary>Create a new Connection. Use this for constructor</summary> public static Connection Create(Node source, Node target, int sourceIndex = -1, int targetIndex = -1) { if (source == null || target == null) { Logger.LogError("Can't Create a Connection without providing Source and Target Nodes"); return(null); } if (source is MissingNode) { Logger.LogError("Creating new Connections from a 'MissingNode' is not allowed. Please resolve the MissingNode node first"); return(null); } var newConnection = (Connection)System.Activator.CreateInstance(source.outConnectionType); UndoUtility.RecordObject(source.graph, "Create Connection"); var resultSourceIndex = newConnection.SetSourceNode(source, sourceIndex); var resultTargetIndex = newConnection.SetTargetNode(target, targetIndex); newConnection.OnValidate(resultSourceIndex, resultTargetIndex); newConnection.OnCreate(resultSourceIndex, resultTargetIndex); UndoUtility.SetDirty(source.graph); return(newConnection); }
//... protected override void OnValidate() { base.OnValidate(); #if UNITY_EDITOR if (UnityEditor.SceneManagement.PrefabStageUtility.GetCurrentPrefabStage() != null) { return; } #endif if (Application.isPlaying || IsPrefabAsset()) { return; } if (!_allGlobals.Contains(this)) { _allGlobals.Add(this); } if (string.IsNullOrEmpty(_identifier)) { _identifier = gameObject.name; } var existing = Find(identifier); if (existing != this && existing != null) { Logger.LogError(string.Format("Another blackboard with the same identifier name '{0}' exists. Please rename either.", identifier), LogTag.BLACKBOARD, this); } }
///Set the target IDialogueActor for the provided key parameter name public void SetActorReference(string paramName, IDialogueActor actor) { var param = actorParameters.Find(p => p.name == paramName); if (param == null) { Logger.LogError(string.Format("There is no defined Actor key name '{0}'", paramName), "Dialogue Tree", this); return; } param.actor = actor; }
///Called after the node has GatherPorts to gather the references and validate the binding connection public void GatherAndValidateTargetPort() { _targetPort = null; //refetch if (targetPort != null) { //all good if (targetPort.type == bindingType) { targetPortID = targetPort.ID; targetPort.connections++; return; } //replace binder connection type if possible if (targetPort is ValueInput && sourcePort is ValueOutput) { if (TypeConverter.HasConvertion(sourcePort.type, targetPort.type)) { graph.RemoveConnection(this); Create(sourcePort, targetPort); targetPortID = targetPort.ID; targetPort.connections++; return; } //the cast is invalid Logger.LogError(string.Format("Input Port with ID '{0}' cast is invalid.", targetPortID), LogTag.VALIDATION, targetNode); targetPort.FlagInvalidCast(); targetPortID = targetPort.ID; targetPort.connections++; return; } } //the id is missing... Logger.LogError(string.Format("Input Port with ID '{0}' is missing on node {1}", targetPortID, targetNode.name), LogTag.VALIDATION, targetNode); var target = targetNode as FlowNode; Port missingPort = null; if (bindingType == typeof(Flow)) { missingPort = target.AddFlowInput(targetPortID, targetPortID, (f) => { throw new System.Exception("Port is missing"); }); } else { missingPort = target.AddValueInput(targetPortID, targetPortID, typeof(object)); } missingPort.FlagMissing(); missingPort.connections++; }
///Adds a new Variable in the blackboard public static Variable AddVariable(this IBlackboard blackboard, string varName, object value) { if (value == null) { Logger.LogError("You can't use AddVariable with a null value. Use AddVariable(string, Type) to add the new variable first", LogTag.BLACKBOARD, blackboard); return(null); } var newVariable = blackboard.AddVariable(varName, value.GetType()); if (newVariable != null) { newVariable.value = value; } return(newVariable); }
protected override bool OnCheck() { if (perceptionTarget.value == null) { Logger.LogError($"<b>Distance To Target</b>: No {nameof(PerceptionTarget)} assigned!", "OnCheck", this); return(false); } if (perceptionTarget.value.Target == null) { return(false); } float distanceToTarget = Vector2.Distance(agent.transform.position, perceptionTarget.value.Target.transform.position); return(OperationTools.Compare(distanceToTarget, distance.value, comparison, 0f)); }
///Set the value of the Variable variable defined by its name. If a data by that name and type doesnt exist, a new data is added by that name public static Variable SetVariableValue(this IBlackboard blackboard, string varName, object value) { Variable variable; if (!blackboard.variables.TryGetValue(varName, out variable)) { Logger.Log(string.Format("No Variable of name '{0}' and type '{1}' exists on Blackboard '{2}'. Adding new instead...", varName, value != null ? value.GetType().FriendlyName() : "null", blackboard), LogTag.BLACKBOARD, blackboard); variable = blackboard.AddVariable(varName, value); return(variable); } try { variable.value = value; } catch { Logger.LogError(string.Format("Can't cast value '{0}' to blackboard variable of name '{1}' and type '{2}'", value != null ? value.ToString() : "null", varName, variable.varType.FriendlyName()), LogTag.BLACKBOARD, blackboard); return(null); } return(variable); }
///---------------------------------------------------------------------------------------------- ///Gets the variable data value from the blackboard with provided name and type T. public static T GetVariableValue <T>(this IBlackboard blackboard, string varName) { var variable = GetVariable <T>(blackboard, varName); if (variable == null) { Logger.LogError(string.Format("No Variable of name '{0}' and type '{1}' exists on Blackboard '{2}'. Returning default T...", varName, typeof(T).FriendlyName(), blackboard), LogTag.BLACKBOARD, blackboard); return(default(T)); } if (variable is Variable <T> ) { return((variable as Variable <T>).value); } try { return((T)variable.value); } catch { Logger.LogError(string.Format("Can't cast value of variable with name '{0}' to type '{1}'", varName, typeof(T).FriendlyName()), LogTag.BLACKBOARD, blackboard); } return(default(T)); }
///Promotes the parameter to a variable on the target blackboard (overriden if parameter name is a path to a global bb). public Variable PromoteToVariable(IBlackboard targetBB) { if (string.IsNullOrEmpty(name)) { varRef = null; return(null); } var varName = name; var bbName = targetBB != null? targetBB.name : string.Empty; if (name.Contains("/")) { var split = name.Split('/'); bbName = split[0]; varName = split[1]; targetBB = GlobalBlackboard.Find(bbName); } if (targetBB == null) { varRef = null; Logger.LogError(string.Format("Parameter '{0}' failed to promote to a variable, because Blackboard named '{1}' could not be found.", varName, bbName), "Variable", this); return(null); } varRef = targetBB.AddVariable(varName, varType); if (varRef != null) { #if UNITY_EDITOR if (NodeCanvas.Editor.NCPrefs.logDynamicParametersInfo) { Logger.Log(string.Format("Parameter '{0}' (of type '{1}') promoted to a Variable in Blackboard '{2}'.", varName, varType.FriendlyName(), bbName), "Variable", this); } #endif } else { Logger.LogError(string.Format("Parameter {0} (of type '{1}') failed to promote to a Variable in Blackboard '{2}'.", varName, varType.FriendlyName(), bbName), "Variable", this); } return(varRef); }
void Internal_RegisterCallback(string message, Delegate callback) { if (string.IsNullOrEmpty(message)) { Logger.LogError("Registration message name is null or empty.", "Events"); return; } List <object> targetObjects = null; if (!listeners.TryGetValue(message, out targetObjects)) { targetObjects = new List <object>(); listeners[message] = targetObjects; } if (!targetObjects.Contains(callback)) { targetObjects.Add(callback); } }
///<summary>Promotes the parameter to a variable on the target blackboard (overriden if parameter name is a path to a global bb).</summary> public Variable PromoteToVariable(IBlackboard targetBB) { if (string.IsNullOrEmpty(name)) { varRef = null; return(null); } var varName = name; var bbName = string.Empty; if (name.Contains("/")) { var split = name.Split('/'); bbName = split[0]; varName = split[1]; targetBB = GlobalBlackboard.Find(bbName); } if (targetBB == null) { varRef = null; Logger.LogError(string.Format("Parameter '{0}' failed to promote to a variable, because Blackboard named '{1}' could not be found.", varName, bbName), LogTag.VARIABLE, this); return(null); } varRef = targetBB.AddVariable(varName, varType); if (varRef != null) { Logger.Log(string.Format("Parameter '{0}' (of type '{1}') promoted to a Variable in Blackboard '{2}'.", varName, varType.FriendlyName(), targetBB), LogTag.VARIABLE, this); } else { Logger.LogError(string.Format("Parameter {0} (of type '{1}') failed to promote to a Variable in Blackboard '{2}'.", varName, varType.FriendlyName(), targetBB), LogTag.VARIABLE, this); } return(varRef); }
///Adds a new Variable in the blackboard defining name and type instead of value public static Variable AddVariable(this IBlackboard blackboard, string varName, Type type) { if (blackboard.variables.TryGetValue(varName, out Variable result)) { if (result.CanConvertTo(type)) { Logger.Log(string.Format("Variable with name '{0}' already exists in blackboard '{1}'. Returning existing instead of new.", varName, blackboard), LogTag.BLACKBOARD, blackboard); return(result); } else { Logger.LogError(string.Format("Variable with name '{0}' already exists in blackboard '{1}', but is of a different type! Returning null instead of new.", varName, blackboard), LogTag.BLACKBOARD, blackboard); return(null); } } var variableType = typeof(Variable <>).RTMakeGenericType(new Type[] { type }); var newVariable = (Variable)Activator.CreateInstance(variableType); newVariable.name = varName; blackboard.variables[varName] = newVariable; blackboard.TryInvokeOnVariableAdded(newVariable); return(newVariable); }
///---------------------------------------------------------------------------------------------- ///Called after the node has GatherPorts to gather the references and validate the binding connection public void GatherAndValidateSourcePort() { _sourcePort = null; //refetch if (sourcePort != null) { //all good if (TypeConverter.HasConvertion(sourcePort.type, bindingType)) { sourcePortID = sourcePort.ID; sourcePort.connections++; return; } //the cast is invalid Logger.LogError(string.Format("Output Port with ID '{0}' cast is invalid.", sourcePortID), LogTag.VALIDATION, sourceNode); sourcePort.FlagInvalidCast(); sourcePortID = sourcePort.ID; sourcePort.connections++; return; } //the id is missing... Logger.LogError(string.Format("Output Port with ID '{0}' is missing on node {1}", sourcePortID, sourceNode.name), LogTag.VALIDATION, sourceNode); var source = sourceNode as FlowNode; Port missingPort = null; if (bindingType == typeof(Flow)) { missingPort = source.AddFlowOutput(sourcePortID, sourcePortID); } else { missingPort = source.AddValueOutput(sourcePortID, sourcePortID, typeof(object), () => { throw new System.Exception("Port is missing"); }); } missingPort.FlagMissing(); missingPort.connections++; }
///Call the functions assigned to the event with argument public bool Dispatch <T>(string message, T arg, object sender = null) { if (sender == null) { sender = this; } List <object> targets; if (!listeners.TryGetValue(message, out targets)) { return(false); } for (var i = 0; i < targets.Count; i++) { var target = targets[i]; if (target == null) { continue; } MethodInfo method = null; if (target is Delegate) { method = (target as Delegate).RTGetDelegateMethodInfo(); } else { method = target.GetType().GetMethod(message, METHOD_FLAGS); } if (method == null) { Logger.LogError(string.Format("Can't resolve method {0}.{1}.", target.GetType().Name, message), "Events", target); continue; } var parameters = method.GetParameters(); if (parameters.Length > 1) { Logger.LogError(string.Format("Parameters on method {0}.{1}, are more than 1.", target.GetType().Name, message), "Events", target); continue; } object[] argsArray = null; if (parameters.Length == 1) { object realArg; if (typeof(MessageData).RTIsAssignableFrom(parameters[0].ParameterType)) { realArg = new MessageData <T>(arg, this.gameObject, sender); } else { realArg = arg; } argsArray = ReflectionTools.SingleTempArgsArray(realArg); } if (target is Delegate) { (target as Delegate).DynamicInvoke(argsArray); } else { if (method.ReturnType == typeof(IEnumerator)) { MonoManager.current.StartCoroutine((IEnumerator)method.Invoke(target, argsArray)); } else { method.Invoke(target, argsArray); } } } return(true); }