public static void Init(InteractionScript script){ instance = (ScriptViewWindow)EditorWindow.GetWindow(typeof(ScriptViewWindow)); // be sure we don't blow away and edits when switching scripts... instance.requestedScript = script; // what if we start running before saving ? we should probably warn for that too. if (!(EditorApplication.isPlaying || EditorApplication.isPaused) && instance.hasChanged && instance.myScript != null && instance.myScript!=instance.requestedScript){ // don't load up yet, put up a confirmation dialog first. instance.confirmChange=true; return; } //EditorUtility.InstanceIDToObject instance.scriptInstanceID = script.GetInstanceID(); instance.myScript = script; instance.title = "Script View"; instance.scriptName = script.name; if (script.transform.parent != null){ instance.myParent = script.transform.parent.GetComponent<ScriptedObject>(); } instance.hasChanged = false; instance.hasBeenRunning = false; EditorApplication.playmodeStateChanged += instance.PlaymodeCallback; }
private void TriggerWithKnife(InteractionScript script) { KnifeInteraction knife = script as KnifeInteraction; if (knife != null) { if (knife.KnifeState == KnifeInteraction.EKnifeState.Screwdriver) { if (!m_openState) { LeanTween.moveLocal(gameObject, new Vector3(1.07f, -0.3f, 0f), 0.3f).setEaseInOutSine().setOnComplete((o => { m_key.gameObject.SetActive(true); })); knife.SetOutLine(false); knife.enabled = false; } else { LeanTween.moveLocal(gameObject, new Vector3(0.24f, 0.09f, 0f), 0.3f).setEaseInOutSine().setOnComplete((o => { m_key.gameObject.SetActive(false); m_holeInteraction.m_isClose = true; })); knife.SetOutLine(false); knife.enabled = false; } } } }
// Start is called before the first frame update private void Start() { _playerObject = GameObject.Find("player"); _playerInteractionLogic = _playerObject.GetComponent <InteractionScript>(); // Initialize the spots list PopulateSpotsList(); }
public void PickUpItem(InteractionScript script) { if (script.m_canPick) { m_carryItem = script; m_carryItem.PickUpItem(m_pickNode.transform); m_interactionItems.Remove(m_carryItem); } }
private void Start() { line = this.gameObject.GetComponent <LineRenderer>(); interactor = new InteractionScript(); ogSpeed = speed; if (!File.Exists("Assets/playerPos.txt")) { File.Create("Assets/playerPos.txt"); } }
private void TriggerTakeOffBook(InteractionScript script) { m_bookSlot.SetActive(false); script.gameObject.SetActive(true); Character character = FindObjectOfType <Character>(); character.PickUpItem(script); GlobalEvent.DispatchEvent("BookCaseUp"); }
void Update() { interaction = GetComponent <InteractionScript>(); if (interaction.safeKey == true) { Debug.Log("got a key"); counter.key = 1; } // countText.text = counter.key.ToString(); countText.text = keyCount.ToString(); }
private void TriggerWithKey(InteractionScript script) { m_aniamtor.Play("Door_Open"); script.gameObject.SetActive(false); Character character = FindObjectOfType <Character>(); character.DropCarryItem(); character.PlayAudio("key_interaction"); m_doorOpened = true; }
void Start() { WarpUI.SetActive(false); GameObject player = GameObject.Find("Player"); locations = player.GetComponent <Locations>(); sf = GameObject.FindGameObjectWithTag("Fader").GetComponent <ScreenFader>(); this.other = player.GetComponent <Collider2D>(); this.player = player.GetComponent <MovementScript>(); this.interactor = player.GetComponent <InteractionScript>(); }
private void OnTriggerExit2D(Collider2D other) { if (other != null && other.gameObject.layer == LayerMask.NameToLayer("InteractiveItem")) { InteractionScript script = other.gameObject.GetComponent <InteractionScript>(); if (script != null) { m_interactionItems.Remove(script); script.SetOutLine(false); } } }
private void Awake() { // Rewired Player _player = ReInput.players.GetPlayer(PlayerId); // Character controller component _cc = GetComponent <CharacterController>(); // Animator _anim = GetComponent <Animator>(); // Interaction _interactScript = GetComponent <InteractionScript>(); // Renderer _renderer = GetComponentInChildren <SkinnedMeshRenderer>(); // Camera Script _cameraScript = camera.GetComponent <CameraScript>(); }
public Target(UnitScript target, InteractionScript action) : base(target, 0.1f) //it would make more sense to pull range from whatever is attacking { if (null == target) { throw new System.ArgumentException("Parameter cannot be null", "target"); } if (null == action) { throw new System.ArgumentException("Parameter cannot be null", "action"); } else { myAction = action; } }
private void TriggerWithKnife(InteractionScript script) { KnifeInteraction knife = script as KnifeInteraction; if (knife != null && knife.KnifeState == KnifeInteraction.EKnifeState.Knife) { m_render.sprite = m_bearOpen; m_book.gameObject.SetActive(true); LeanTween.moveX(m_book.gameObject, transform.position.x - 0.2f, 0.3f).setEaseInOutSine(); LeanTween.moveY(m_book.gameObject, transform.position.y + 0.1f, 0.15f).setEaseInCirc(); LeanTween.moveY(m_book.gameObject, transform.position.y - 0.1f, 0.15f).setEaseInCirc().setDelay(0.15f); m_canPick = false; m_canShowOutline = false; } }
void Awake() { MainCamera.SetActive(true); QuestAudioSource = transform.GetChild(0).GetComponent <AudioSource>(); PlayerTransform = transform.parent.GetComponent <Transform> (); playerController = PlayerTransform.GetComponent <PlayerControllerTwo> (); interactionScript = GetComponent <InteractionScript>(); Headline.text = QuestTrackingHEADLINE[CurrentQuest]; Description.text = QuestTrackingTEXT[CurrentQuest]; Description.color = Color.red; QuestTrackingAnimator.SetTrigger("swishIn"); }
void TriggerClick(object sender, ClickedEventArgs e) { //Try to activate held object if (heldObject != null) { WeaponController wc = heldObject.GetComponent <WeaponController>(); if (wc != null) { wc.TriggerClick(); } } //Try to activate touched object else if (touchedObject != null) { InteractionScript interScri = touchedObject.GetComponent <InteractionScript>(); interScri.Interact(); } }
private void TriggerWithBook(InteractionScript script) { // // script.transform.parent = transform; // script.transform.localPosition = Vector3.zero; m_bookSlot.SetActive(true); Character character = FindObjectOfType <Character>(); character.DropCarryItem(); script.gameObject.SetActive(false); GlobalEvent.DispatchEvent("BookCaseDown"); // LeanTween.moveLocal(gameObject, m_downPosition, 0.3f).setEaseInOutSine().setOnComplete((o => // { // GlobalEvent.DispatchEvent("BookCaseDown"); // })); }
private void TriggerWithCaseKey(InteractionScript script) { GlobalEvent.DispatchEvent("Box_Opened"); CaseKeyInteraction caseKey = script as CaseKeyInteraction; if (caseKey != null) { m_aniamtor.Play("Box_Open"); script.gameObject.SetActive(false); Character character = FindObjectOfType <Character>(); character.DropCarryItem(); character.PlayAudio("key_interaction"); m_key.gameObject.SetActive(true); LeanTween.moveLocalX(m_key.gameObject, -3.05f, 0.5f).setEaseInOutSine(); LeanTween.moveLocalY(m_key.gameObject, 0.62f, 0.25f).setEaseInCirc(); LeanTween.moveLocalY(m_key.gameObject, -0.22f, 0.25f).setEaseOutCirc().setDelay(0.25f); } }
private void OnTriggerEnter2D(Collider2D other) { if (other != null && other.gameObject.layer == LayerMask.NameToLayer("InteractiveItem")) { InteractionScript script = other.gameObject.GetComponent <InteractionScript>(); if (script != null) { m_interactionItems.Add(script); script.SetOutLine(true); } } if (other != null) { AintAttack aintAttack = other.GetComponent <AintAttack>(); if (aintAttack != null) { GameSceneManager.Instance.LoadScene("Empty"); } } }
//it would make more sense to pull range from whatever is attacking public Target(UnitScript target, InteractionScript action) : base(target, 0.1f) { if (null == target) { throw new System.ArgumentException("Parameter cannot be null", "target"); } if (null == action) { throw new System.ArgumentException("Parameter cannot be null", "action"); } else { myAction = action; } }
// handles messages coming back from the GUI. these messages are setup in the DialogMsg, // and passed when the button button specified. The messages can be either an "onbutton=" event or // a default "button" event public bool ProcessMessage(string msg) { bool handled = false; // make lower case version string msgLower = msg.ToLower(); if (msgLower.Contains("onbutton=") || msgLower.Contains("interact=") || msgLower.Contains("script=") || msgLower.Contains("audio=") || msgLower.Contains("action=")) { // check name of pressed button string buttonName; if ( GetToken(msgLower, "onbutton", out buttonName) == true ) { if ( msgLower.Contains("pressed")) { string pressedName; if ( GetToken(msgLower,"pressed", out pressedName) == true ) { // if button pressed is not equal to this action, return if ( buttonName != pressedName ) return false; } } } if (msgLower.Contains("interact=")) { // get rid of tag string map; if (GetToken(msg, "interact", out map) == true) // this used to process msgLower, but produced unmatchable tags { // create interaction map InteractionMap imap; // lookup interaction map imap = InteractionMgr.GetInstance().Get(map); if (imap == null) { // not found, generic...make one imap = new InteractionMap(map, null, null, null, null, null, null, true); } // get object to send to....if no object then assume that we are sending msg to script owner BaseObject obj = null; // first look for object token string _object; if (GetToken(msgLower, "object", out _object) == true) { // we have an object, go find it // get object obj = ObjectManager.GetInstance().GetBaseObject(_object); } else { // sending msg to script owner if ( executedBy != null && executedBy.caller != null ) obj = executedBy.caller.ObjectInteraction; } // send to object if we have one! if (obj != null) { if ( executedBy.debug == true ) UnityEngine.Debug.Log("GUIButton.ProcessMessage() : obj=" + obj.name + " : map=" + map); // create InteractMsg InteractMsg imsg = new InteractMsg(obj.gameObject, imap); imsg.map.confirm = false; obj.PutMessage(imsg); } else { if ( executedBy.debug == true ) UnityEngine.Debug.Log("GUIButton.ProcessMessage() : can't find obj=" + obj.Name + " : map=" + map); } } } // this is the audio handling block. Allows audio to play on button if (msgLower.Contains("audio")) { string audio; if (GetToken(msgLower, "audio", out audio) == true) { // play some audio Brain.GetInstance().PlayAudio(audio); } } // this is the script handling block. the specified script will be executed on either the // calling object or on the object=obj specified. system queues the script on the ScriptedObject // to be completed after the object is finished with the current script. if (msgLower.Contains("script=")) { string _script; // NOTE!! don't use lower case here because scripts need to be literal if (GetToken(msg, "script", out _script) == true) { BaseObject obj=null; // get object to send script too string _object; if (GetToken(msgLower, "object", out _object) == true) { // we have an object, go find it obj = ObjectManager.GetInstance().GetBaseObject(_object); } else { // no target, sending msg to script owner if ( executedBy != null && executedBy.caller != null ) obj = executedBy.caller.ObjectInteraction; } // split to see if we have multiple scripts string[] scripts = _script.Split(','); // process all of them foreach ( string item in scripts ) { BaseObject thisObj = obj; string thisItem = item; // so we can assign // added feature to allow sending the object name along with the script name, using "@" if (item.Contains("@")){ string[] parts = item.Split('@'); thisItem = parts[1]; if (ObjectManager.GetInstance().GetBaseObject(parts[0])!= null) thisObj = ObjectManager.GetInstance().GetBaseObject(parts[0]); } // send it if ( thisObj != null ) { // we have a valid object and script....execute it! if ( executedBy.debug == true ) UnityEngine.Debug.Log("ScriptedAction.ProcessMessage(" + msgLower + ") script=" + thisItem + " : object=" + thisObj.Name); // try finding the named game object and look for an interaction script there GameObject isGO = GameObject.Find(thisItem); if (isGO != null) scriptToExecute = isGO.GetComponent<InteractionScript>(); if (scriptToExecute != null){ //build a string with our script's args and add to stringParam args... string paramString = "trigger=" + "DIALOG" ; ScriptedObject sObj = thisObj.GetComponent<ScriptedObject>(); if (sObj != null) sObj.QueueScript(scriptToExecute, paramString, thisObj.gameObject); else executedBy.caller.QueueScript(scriptToExecute, paramString, thisObj.gameObject); // yield until we get an update. which will complete us. we HAVE to wait, no multi threading support yet. waitingForUpdate = true; } else { if ( executedBy.debug == true ) Debug.LogError("scriptedAction could not find script to execute at "+name+executedBy.name); waitingForUpdate = true; handled = true; // should probably do this in the other branches as well...s } } } } } // all buttons execpt for close must provide either action=abort, or action=ok to // make the dialog continue execution. We do this because we have to have the buttons // be able to continue scripts if (msgLower.Contains("action")) { string action; if (GetToken(msgLower, "action", out action) == true) { if ( executedBy.debug == true ) UnityEngine.Debug.Log("ScriptedAction.ProcessMessage() : action=" + action); // set specific lines based on action if ( action == "abort" ) { executedBy.nextLineLabel = "abort"; // this is setting the abort case error = "abort"; // this is error case handled = true; } if ( action == "else" ) { if (dialogIfThen){ // either treat like if-then, or abort executedBy.nextLineLabel = "else"; } else{ executedBy.nextLineLabel = "abort"; error = "abort"; } handled = true; } if ( action == "ok" || action == "close" ) { executedBy.nextLineLabel = ""; // this means just continue execution handled = true; } } } // this is not a closer return handled; } // Default button handling... if ( msgLower.Contains("button") ) { string button; if (GetToken(msgLower, "button", out button) == true) { if ( executedBy.debug == true ) UnityEngine.Debug.Log("ScriptedAction.ProcessMessage() : button=" + button); switch( button.ToLower() ) { case "close": case "cancel": case "buttonnext": // traumaQuickFast sends this if (dialogIfThen){ // either treat like if-then, or abort executedBy.nextLineLabel = "else"; } else{ executedBy.nextLineLabel = "abort"; error = "abort"; } handled = true; break; case "ok": executedBy.nextLineLabel = ""; handled = true; break; } } } return handled; }
public void InsertScriptAt(InteractionScript script, int desiredIndex){ // if index greater than length, append if (desiredIndex > scripts.Length) desiredIndex = scripts.Length; InteractionScript[] newScripts = new InteractionScript[scripts.Length+1]; for (int i=0; i<desiredIndex; i++){ newScripts[i] = scripts[i]; } newScripts[desiredIndex] = script; for (int i=desiredIndex; i<scripts.Length; i++){ newScripts[i+1] = scripts[i]; } scripts = newScripts; script.transform.parent = this.transform; }
public void DoInteraction(string interactionName) { bool found = false; eventScript = null; string argString = ""; if (interactionName.Contains("?")){ // process any affixed parameters, including 'script=', which must appear first if included // arguments should be of the form ?name=value?name=value?name=value // and can be referenced as script arguments within the animationScript as #name. // the expression ?name=value may include ?name=#arg or ?name=%variable and substitution should occur // in the originating script //(not implemented in the first pass) string[] p = interactionName.Split ('?'); interactionName = p[0]; animSpeed = 1; // for overrideing defaults animWeight = 1; animTime = 0; int start=1; if (p[1].ToLower().Contains("script=")){ start=2; string[] q = p[1].Split('='); foreach (InteractionScript IS in animationScriptObject.scripts){ if (IS.name == q[1]){ eventScript = IS; scriptNameOverride = true; } } } // process speed= weight= time= possibly mixing transform... while (start < p.Length){ if (p.Length > start && p[start].ToLower().Contains("speed=")){ string[] q = p[start].Split('='); float.TryParse(q[1],out animSpeed); } if (p.Length > start && p[start].ToLower().Contains("weight=")){ string[] q = p[start].Split('='); float.TryParse(q[1],out animWeight); } if (p.Length > start && p[start].ToLower().Contains("time=")){ string[] q = p[start].Split('='); float.TryParse(q[1],out animTime); } start++; } body.animation[p[0]].speed = animSpeed; body.animation[p[0]].weight = animWeight; // weight gets overridden by crossfade. if (animTime >= 0) // use -1 to keep animation where it is but change it's speed... body.animation[p[0]].time = animTime; // setting this beyond the initial anim event breaks the anim system, we might need to fake the skipped anim event for (int i=start;i<p.Length; i++){ argString += p[i]; if (i<p.Length-1) argString+=" "; } } //Debug.Log ("!!!!!!" + name + " Doing Interaction " + interactionName); for(int c = 0; c < interactions.Count; c++) { if(interactionName == interactions[c].Name) { found = true; currentInteraction = interactions[c]; if(animQueue.Count > 0) RemoveLastAnim(); foreach(AnimationClip ac in interactions[c].AnimClips) { if(ac != null && body.animation[ac.name] != null) // we might have one to load from resources animQueue.Enqueue(ac); else Debug.LogWarning(gameObject.name + " loading null Interaction Animation for " + interactions[c].Name); } if(baseClip != null) animQueue.Enqueue(baseClip); idleEnabled = false; // we now search for a script name==currentAnim when an event is triggered,, so this check may be un needed. /* if (eventScript == null){ // look for a default eventScript matching the animation name foreach (InteractionScript IS in animationScriptObject.scripts){ if (IS.name == interactionName) eventScript = IS; } } */ if(animState == CharacterAnimState.Idle) PlayNext(0.5f); // careful, PlayNext clears eventScript... //return; //we've done one, we should leave now. continue; } } if (found == false) { // see if there's a clip of this name on our animator AnimationClip aClip = null; if (body.animation[interactionName] != null) aClip = body.animation[interactionName].clip; // do we want to be saving animation states ? if (aClip == null){ // or a clip we loaded from resources if (maleClips.ContainsKey (interactionName)){ // have to check based on m/f aClip = maleClips[interactionName]; body.animation.AddClip(aClip,interactionName); } // if so, add it to our animations } if (aClip != null){ // inefficient, but let's see if there's a matching script here for now. //we should look in the resources folder for these, too. if (eventScript == null){ // look for a default eventScript matching the animation name foreach (InteractionScript IS in animationScriptObject.scripts){ if (IS.name == interactionName) eventScript = IS; scriptNameOverride = true; // adding this so playnext doesn't clear. seems wrong. } } if(animQueue.Count > 0) RemoveLastAnim(); animQueue.Enqueue(aClip); if(baseClip != null) animQueue.Enqueue(baseClip); idleEnabled = false; if(animState == CharacterAnimState.Idle) PlayNext(0.5f); // careful, PlayNext clears eventScript... } currentInteraction = null; // do we need to make one of these, or is this what we should save? } if (eventScript != null){ if (argString != ""){ eventScript.startingArgs = argString; // this replaces and overrides any editor supplied values... } // pass along arguments from the script that called this DoInteraction // there may be some confusion here about which script it was. TaskCharacter tc = GetComponent<TaskCharacter>(); ScriptedAction sa = null; if (tc != null) sa=tc.executingScript; if (sa!=null && sa.executedBy!= null){ eventScript.startingArgs += " "+sa.executedBy.GetArgs(); } } }
void DeleteScriptLine(InteractionScript script, int index){ ScriptedAction lineToDelete = script.scriptLines[index]; // delete from the list ScriptedAction[] tmp = new ScriptedAction[script.scriptLines.Length]; for (int i=0; i < script.scriptLines.Length; i++){ tmp[i]= script.scriptLines[i]; } script.scriptLines = new ScriptedAction[tmp.Length-1]; for (int i=0; i < index; i++){ script.scriptLines[i] = tmp[i]; } for (int i=index+1; i < tmp.Length; i++){ script.scriptLines[i-1] = tmp[i]; } // clean up the game object. DestroyImmediate(lineToDelete.gameObject); // that should get rid of all the components, too? }
// Start is called before the first frame update void Start() { Cursor.lockState = CursorLockMode.Locked; interactionScript = new InteractionScript(); }
int AddLines(InteractionMap map, InteractionScript IS, int index){ // if we have an interaction list, then accumulate the number of character tasks in each map's task if (map.list != null && map.list.Length > 0){ // foreach isn't guaranteed to traverse in order, should index foreach (Interaction intr in InteractionMgr.GetInstance ().GetList(map.list).Interactions){ index = AddLines(intr.Map,IS,index); } } else { // no list. if we have a task, then add lines for each character tasks in it's data if (map.task != null && TaskMaster.GetInstance().GetTask(map.task) != null && TaskMaster.GetInstance().GetTask(map.task).data != null && TaskMaster.GetInstance().GetTask(map.task).data.characterTasks != null) { int hasSound = 0; if (map.sound != null && map.sound != "" ){ hasSound = 1; Debug.Log ("found sound"); } ScriptedAction SA = BuildSendInteractMessage(map); IS.scriptLines[index] = SA; // build the unity hierachy SA.gameObject.transform.parent = IS.gameObject.transform; index++; // add handling the sound here from the interaction map if (hasSound > 0) { SA = BuildPlaySound(map.sound); IS.scriptLines[index] = SA; // build the unity hierachy SA.gameObject.transform.parent = IS.gameObject.transform; index++; } int lineCount = TaskMaster.GetInstance().GetTask(map.task).data.characterTasks.Count; foreach (CharacterTask c in TaskMaster.GetInstance().GetTask(map.task).data.characterTasks) { SA = BuildLineFromCharacterTask(c); IS.scriptLines[index] = SA; // build the unity hierachy SA.gameObject.transform.parent = IS.gameObject.transform; index++; } // crosslink the lines within this character task to wait for each other, if (lineCount > 1){ for (int sai = index-lineCount; sai<index; sai++){ IS.scriptLines[sai].syncToTasks = new ScriptedAction[lineCount-1]; int insertPtr = 0; for (int linkPtr = index-lineCount; linkPtr < index; linkPtr++){ if (linkPtr != sai) IS.scriptLines[sai].syncToTasks[insertPtr++] = IS.scriptLines[linkPtr]; } } } // set the COMPLETE mesasge on the last one, and WaitForCompletion only on the last one IS.scriptLines[index-1].stringParam4 = map.item+":COMPLETE"; IS.scriptLines[index-1].waitForCompletion = true; } else { ScriptedAction SAE = BuildLineFromMap(map); IS.scriptLines[index] = SAE; // build the unity hierachy SAE.gameObject.transform.parent = IS.gameObject.transform; index++; // this is really an error condition we need to resolve } } return index; }
public void Update() { if (!m_canInput) { return; } m_movement.x = Input.GetAxisRaw("Horizontal"); //m_movement.y = Input.GetAxisRaw("Vertical"); if (m_movement == Vector2.zero) { string animName = m_carryItem != null ? "Pick_Idle" : "Idle"; m_footAudio.Stop(); PlayAnimation(animName, m_movement.x, m_recordY); } else { m_recordY = m_movement.y; if (!m_footAudio.isPlaying) { m_footAudio.Play(); } string animName = m_carryItem != null ? "Pick_Walk" : "Walk"; PlayAnimation(animName, m_movement.x, m_recordY); } if (m_interactionItems.Count > 0) { //交互 if (Input.GetKeyDown(KeyCode.Space)) { for (int i = 0; i < m_interactionItems.Count; i++) { bool result = m_interactionItems[i].TriggerEnterAction(); if (result) { return; } } return; } if (m_carryItem == null) { float distance = float.MaxValue; InteractionScript item = null; if (Input.GetKeyDown(KeyCode.E)) { for (int i = 0; i < m_interactionItems.Count; i++) { //捡起、放下 if (m_interactionItems[i].m_canPick) { float dis = Vector2.Distance(transform.position, m_interactionItems[i].transform.position); if (dis < distance) { distance = dis; item = m_interactionItems[i]; } } } if (item != null) { m_carryItem = item; m_carryItem.PickUpItem(m_pickNode.transform); m_interactionItems.Remove(m_carryItem); } return; } } } if (m_carryItem != null && Input.GetKeyDown(KeyCode.E)) { m_carryItem.DropDownItem(transform); m_carryItem = null; } }
void Update() { Vector3 newScale = transform.localScale; /* Prevent y velocity to buffer while we're grounded or hitting ceiling */ if (controller.collisions.above || controller.collisions.below) { velocity.y = 0; } /* Jump, controls & gravity */ Vector2 input = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")); if (input.x == -1) { faceDirection = 1; } else if (input.x == 1) { faceDirection = -1; } if (Input.GetAxisRaw("Jump") > 0) { timeJumpWasCalled = Time.timeSinceLevelLoad; } /* Interactions ! */ RaycastHit2D hit; if (Input.GetAxisRaw("Fire1") > 0) { if (hit = controller.ManualRayCast(InteractionLayer, -faceDirection, 0, 2.0f)) // Change length maybe ? { InteractionScript interaction = hit.transform.gameObject.GetComponent <InteractionScript>(); interaction.Interact(gameObject); } } if (hit = controller.ManualRayCast(EnemyLayer, -faceDirection, 0, 2.0f)) // Change length maybe ? { InteractionScript interaction = hit.transform.gameObject.GetComponent <InteractionScript>(); interaction.Interact(gameObject); } float TargetHorizontalVelocity = input.x * stats.moveSpeed; velocity.x = Mathf.SmoothDamp(velocity.x, TargetHorizontalVelocity, ref velocityXSmoothing, controller.collisions.below ? stats.groundedAcceleration : stats.airborneAcceleration); // Before gravity, otherwise we're always moving if (Mathf.Abs(velocity.x) < 0.1f && Mathf.Abs(velocity.y) < 0.1f) { playerState = PlayerState.IDLE; } else if (controller.collisions.below) { playerState = PlayerState.MOVING; } else if (velocity.y > 0.1f) { playerState = PlayerState.JUMPING; } else { playerState = PlayerState.DOWN; } anim.SetInteger("State", (int)playerState); velocity.y += gravity * Time.deltaTime; }
public void Execute(InteractionScript callingScript){ //Debug.Log ("XXX"+Time.time+" "+name+type); if ((breakpoint || callingScript.singleStepping) && callingScript.debug){ // place a breakpoint here and set breakpoint=true to trap on execute of a particular line of script Debug.Log ("Hit Execute Breakpoint for "+name+" of "+callingScript.name); InteractionScript.atBreakpoint = callingScript; callingScript.waitingForDebugger = true; Debug.Break (); WaitForDebugger (callingScript); Debug.Log ("Ran Right Past the Call"); } executedBy = callingScript; /* moved to Calling script to handle Role mapping * if (objectToAffect == null){ // default, or we could try looking up the name again... if (objectName != ""){ objectToAffect = GameObject.Find(executedBy.ResolveArgs(objectName).Replace ("\"","")); // we have a problem with two names here, one used by unity, one by the if (objectToAffect == null){ objectToAffect = ObjectManager.GetInstance().GetGameObject(objectName); } } else objectToAffect = executedBy.myObject; } */ if (executedBy != null) objectToAffect = executedBy.FindObjectToAffect(this); if (type != actionType.putMessage && objectToAffect != null) // don't need a taskCharacter to send a message... taskChar = objectToAffect.GetComponent<TaskCharacter>(); if (!forceExecute){ if (taskChar != null && taskChar.executingScript != null && taskChar.executingScript != this){ // this character is already busy, so wait until the current line completes StartCoroutine (ExecuteWhenIdle(callingScript)); return; } if (taskChar != null){ taskChar.executingScript = this; if (taskChar.actingInScript != null && taskChar.actingInScript != executedBy){// && CanCompleteImmediately()){ // don't add me, I'll be done before you know it... } else { taskChar.actingInScript = executedBy; // this could get cleared by this character doing an executeScript. // since we set it, be sure we're in the list of actor objects so we'll be released if (!executedBy.actorObjects.Contains(taskChar as ObjectInteraction)) executedBy.actorObjects.Add (taskChar as ObjectInteraction); } } } forceExecute = false; #if DEBUG_SCRIPTING Debug.Log ("ScriptedAction execute "+name); #endif if (breakpoint && callingScript.debug){ // place a breakpoint here and set breakpoint=true to trap on execute of a particular line of script Debug.Log ("Hit Execute Breakpoint for "+name+" of "+callingScript.name); } if (hasExecuted && executeOnlyOnce){ error = "already executed"; OnComplete(); } characterTaskPending = false; waitingForUpdate = false; // a single update call will complete us waitingForDialog = false; taskReady = false; waitingForNav = false; waitingForCondition = false; ignoreTimeout = false; waitingForAnim = false; runIndependentUpdates = false; trackCameraLookat = false; postureChangeStartTime = 0; executedBy = callingScript; error = ""; this.enabled = true; // need updates until we are through // Temporary hack to add any InteractMessage map to the character to avoid an error if (objectToAffect != null && type == actionType.putMessage && gameMsgForm.msgType == GameMsgForm.eMsgType.interactMsg){ // we are going to add this interaction to the objects AllMaps so it doesn't get an error ObjectInteraction OI = objectToAffect.GetComponent<ObjectInteraction>(); if (OI != null) OI.AddToAllMaps(gameMsgForm.map.GetMap()); } if (preAttributes != "") SetAttributes(objectToAffect,preAttributes); // can't do this here, need to do it when we use the values, and don't overwrite the original ones! // stringParam = SubstituteArgsAndAttributes(stringParam); // update parameter strings with current #args, $attrs // stringParam2 = SubstituteArgsAndAttributes(stringParam2); // stringParam3 = SubstituteArgsAndAttributes(stringParam3); // stringParam4 = SubstituteArgsAndAttributes(stringParam4); // attachmentOverride = SubstituteArgsAndAttributes(attachmentOverride); if (type == actionType.enableInteraction){ if (objectName == "Dispatcher"){ // this will cause all interaction tags except the space delimited list to be rejected // until an interaction on the list is hit, which then re-enables all interactions. // (needed so scripts can use tags to trigger things when running) // an empty list will allow all interactions again. Dispatcher td = FindObjectOfType<Dispatcher>(); if (td != null){ td.LimitInteractions( stringParam, negate, loop ); } OnComplete(); Cleanup (); } else { // look for an ObjectInteraction component on ObjectToAffect if (objectToAffect != null){ if (objectToAffect.GetComponent<ObjectInteraction>() != null){ ObjectInteraction OI = objectToAffect.GetComponent<ObjectInteraction>(); OI.Enabled = !negate; if (ease || texture2D!= null){ //hackfully abuse the 'ease' boolean to force clear the icon texture if (ease) OI.iconTexture = null; else if (texture2D!= null) OI.iconTexture = texture2D; } } else // adding handling of nav mesh obstacle here... if (objectToAffect.GetComponent<NavMeshObstacle>() != null){ NavMeshObstacle NMO = objectToAffect.GetComponent<NavMeshObstacle>(); NMO.enabled = !negate; } OnComplete(); Cleanup (); } else { error = "no objectInteraction to enable"; OnComplete(); Cleanup (); } } } if (type == actionType.playAnimation){ if (objectToAffect != null){ taskChar = objectToAffect.GetComponent<TaskCharacter>(); if (taskChar != null){ taskChar.Animate(stringParam); // figure out if we should wait... we could wait for the characterAnimState if (waitForCompletion){ waitingForAnim = true; animEndTime = -1; // failsafe for hung waiting for anim to end... AnimationState ast = taskChar.GetComponent<AnimationManager>().body.animation[stringParam]; if (ast != null && ast.clip != null) animEndTime = Time.time + ast.clip.length + 0.05f;; } else OnComplete (); } else { // handle ?speed= ?time= ?wieght= string[] p = stringParam.Split ('?'); string animationName = p[0]; float animSpeed = 1; // for overrideing defaults float animWeight = 1; float animTime = 0; int start=1; // process speed= weight= time= possibly mixing transform... while (start < p.Length){ if (p.Length > start && p[start].ToLower().Contains("speed=")){ string[] q = p[start].Split('='); float.TryParse(q[1],out animSpeed); } if (p.Length > start && p[start].ToLower().Contains("weight=")){ string[] q = p[start].Split('='); float.TryParse(q[1],out animWeight); } if (p.Length > start && p[start].ToLower().Contains("time=")){ string[] q = p[start].Split('='); float.TryParse(q[1],out animTime); } start++; } if (objectToAffect.animation != null){ if (animTime == 0) objectToAffect.animation.Rewind(animationName); if (animTime > 0) objectToAffect.animation[animationName].time = animTime; objectToAffect.animation[animationName].speed = animSpeed; objectToAffect.animation[animationName].weight = animWeight; objectToAffect.animation.clip = objectToAffect.animation[animationName].clip; objectToAffect.animation.Play(); if (waitForCompletion) waitingForAnim = true; else OnComplete (); } } } else { error = "no object to play animation on"; OnComplete(); Cleanup (); } } if (type == actionType.playAudio){ // object to affect should have an audio source AudioSource src = null; if (objectToAffect != null) src = objectToAffect.GetComponent<AudioSource>(); if (src == null) src = objectToAffect.AddComponent<AudioSource>() as AudioSource; if (src != null){ float timeToWait = fadeLength; if (audioClip == null){ // find the audio clip, looking thru the sound map for this character? if (stringParam != ""){ VoiceMap vm = VoiceMgr.GetInstance().Find(objectToAffect.name, stringParam); if (vm != null){ vm.Clip = SoundMgr.GetInstance().GetClip(vm.Audio); if (vm.Clip != null) timeToWait += vm.Clip.length; VoiceMgr.GetInstance().Play (objectToAffect.name, stringParam); if (stringParam2 != "" && taskChar != null && vm.Clip != null) taskChar.LookAt(stringParam2, Time.time + vm.Clip.length); } else{ audioClip = SoundMgr.GetInstance().Get(stringParam); } } } if (audioClip != null){ // will still be null if we sent this to the voice manager src.clip = audioClip; src.Play(); timeToWait += audioClip.length; if (stringParam2 != "" && taskChar != null) taskChar.LookAt(stringParam2, Time.time + audioClip.length); } if (waitForCompletion) StartCoroutine(CompleteAfterDelay (timeToWait)); else { OnComplete(); Cleanup (); } } else { error = "no audiosource for playAudio"; OnComplete(); } } if (type == actionType.putMessage){ // hack to avoid 'I'm too busy messages... if (taskChar != null) taskChar.executingScript = null; StartCoroutine(SendMessageAfterDelay(fadeLength)); } if (type == actionType.move){ // // lets handle the camera move first: if (moveTo == null){ // translate the name, if presesnt if (moveToName != "" && GameObject.Find(moveToName)!= null ){ moveTo = GameObject.Find(moveToName).transform; } } CameraLERP cameraLERP = objectToAffect.GetComponent<CameraLERP>(); if (cameraLERP != null){ // strangely in Unity, we're not allowed to create new Transforms, so we have to make a dummy if (moveTo != null){ if (offset == Vector3.zero){ // assume this is a return to the spline // reset the camera rail controller so we go to the starting position... // CameraRailCoordinator crc = FindObjectOfType<CameraRailCoordinator>(); // if (crc != null) // crc.Reset(); // cameraLERP.MoveTo(moveTo, fadeLength,true,false, 0); trackCameraLookat = true; if (!waitForCompletion) runIndependentUpdates = true; StartCoroutine( EndTrackCameraLookat(fadeLength)); if (!waitForCompletion) OnComplete (); return; } else { dummyGO = new GameObject("dummyGO"); dummyGO.transform.position = moveTo.position + offset.x*dummyGO.transform.forward + offset.y*dummyGO.transform.up + offset.z*dummyGO.transform.right; dummyGO.transform.LookAt(moveTo); cameraLERP.MoveTo(dummyGO.transform, fadeLength,true,true, 0); } } else { if (fadeLength <= 0) cameraLERP.Return(); // snap back else { GameObject dummyGO = new GameObject("dummyGO"); dummyGO.transform.position = cameraLERP.oldWorldPos; dummyGO.transform.rotation = cameraLERP.oldWorldRot; cameraLERP.MoveTo(dummyGO.transform, fadeLength,true,false, 0); } } //Destroy (dummyGO); destroy this later on Completed if (waitForCompletion && fadeLength > 0) StartCoroutine(CompleteAfterDelay (fadeLength)); else { OnComplete(); //Cleanup (); } } else { // if the moveTo NAME is a valid Node Name, we can use the TaskCharacter to move there taskChar = objectToAffect.GetComponent<TaskCharacter>(); if (taskChar != null){ // bool bResult = taskChar.IsInPosition (moveTo.name); // this should start off the nav // lets see if we have something with a NavMeshAgentWrapper... // navWrapper = objectToAffect.GetComponent<NavMeshAgentWrapper>(); // if (navWrapper != null){ // lets ignore the offset for now... // navWrapper.MoveToGameObject(moveTo.gameObject,2.0f); if (waitForCompletion){ navStartTime = Time.realtimeSinceStartup; // we may want to time out waitingForNav = true; return; } else{ runIndependentUpdates = true; pingTaskCharacter = true; OnComplete(); } // } } else { error = "move only implemented for camera, no cameraLERP found"; OnComplete(); } } } if (type == actionType.fade){ // if (objectToAffect == null){ Debug.LogWarning("Null object "+objectName+" for fade by "+name); OnComplete(); Cleanup(); return; } // if the thing is a the GUIManager then fade it GUIManager gm = objectToAffect.GetComponent<GUIManager>(); // test it if (gm != null) { gm.SetFadeCurtain(desiredColor.a, fadeLength); OnComplete(); Cleanup (); return; } // we need to have an object with a renderer. if (objectToAffect != null && objectToAffect.renderer != null){ // if string param has something, look for a resource by that name that is a mesh or material to swap in Material newMaterial = null; // Mesh newMesh = null; if (stringParam != ""){ newMaterial = Resources.Load(stringParam) as Material; // newMesh = Resources.Load(stringParam) as Mesh; } // fade can be an instant change, or take some time. // desired color should override desired alpha if (stringParam=="current"){ // should check new material and use it's color if provided desiredColor = objectToAffect.renderer.material.color; desiredColor.a = desiredAlpha; } desiredColor.a = desiredAlpha; if (fadeLength > 0){ // get components // if the thing has a color changer, lets make use of that. ColorChanger cc = objectToAffect.GetComponent<ColorChanger>(); if (cc != null){ cc.ChangeColor(desiredColor, fadeLength); } else { // fadeBeginTime = Time.time; // fadeBeginColor = objectToAffect.renderer.material.color; if (desiredAlpha > 0){ objectToAffect.renderer.enabled = true; // temporarily just jam the final result until the fade interpolate is in place objectToAffect.renderer.material.color = desiredColor; } // if the final alpha is zero, then set the alpha, and turn off the renderer else { objectToAffect.renderer.enabled = false; objectToAffect.renderer.material.color = desiredColor; } } } else { // instant fade if (newMaterial != null) renderer.material = newMaterial; // if final alpha is > 0, turn the renderer on and set the alpha if (desiredAlpha > 0){ objectToAffect.renderer.enabled = true; objectToAffect.renderer.material.color = desiredColor; } // if the final alpha is zero, then set the alpha, and turn off the renderer else { objectToAffect.renderer.enabled = false; objectToAffect.renderer.material.color = desiredColor; } } } else { // missing object or renderer error = "Fade has no object with renderer specified"; } OnComplete(); Cleanup (); } if (type == actionType.ifThenElse){ // BaseObject bob = null; if (objectToAffect != null && objectToAffect.GetComponent<BaseObject>() != null) bob = objectToAffect.GetComponent<BaseObject>(); if (bob != null){ // build a binaryExpressionNode out of the string for our testEntity and evaluate. // perform any arg substitutions string newString = executedBy.ResolveArgs(stringParam); BinaryExpressionNode condition = BinaryExpressionNode.BuildTree(newString); if (condition.Evaluate(bob)) executedBy.nextLineLabel = ""; // just go on to the next statement else executedBy.nextLineLabel = "else"; // this will find either the next 'else' block or the next 'endIfThenElse' block } else { error = "no baseObject for ifThenElse to test"; } // executedBy.nestingDepth += 1; OnComplete(); Cleanup (); } if (type == actionType.executeScript){ // our execution will be stacked and we will pend until this script completes if (scriptToExecute == null && stringParam2 != null && stringParam2 != ""){ // First, look for a script on the character running this interaction if (taskChar != null){ ScriptedObject tcso = taskChar.GetComponent<ScriptedObject>(); if (tcso!=null){ foreach (InteractionScript tcis in tcso.scripts){ if (tcis.name == stringParam2){ scriptToExecute = tcis; break; } } } } if (scriptToExecute == null){ // try finding the named game object and look for an interaction script there GameObject isGO = GameObject.Find(stringParam2); if (isGO != null) scriptToExecute = isGO.GetComponent<InteractionScript>(); } } if (scriptToExecute == null){ Debug.LogError("scriptedAction could not find script to execute at "+name+executedBy.name); OnComplete (); Cleanup (); } if (waitForCompletion){ // run this as a subroutine, continuing when it's done //build a string with our script's args and add to stringParam args... if (taskChar != null) taskChar.executingScript = null; // need to clear this for the next scrip executedBy.ExecuteScript(scriptToExecute, executedBy.ResolveArgs(stringParam)+" trigger="+name, objectToAffect, ease); // yield until we get an update. which will complete us. we HAVE to wait, no multi threading support yet. waitingForUpdate = true; } else { // don't wait for completion, so we will JUMP and not return to this line if (taskChar != null) taskChar.executingScript = null; // need to clear this for the next scrip executedBy.QueueScript(scriptToExecute, executedBy.ResolveArgs(stringParam)+" trigger="+name, objectToAffect, ease); // yield until we get an update. which will complete us. we HAVE to wait, no multi threading support yet. executedBy.nextLineLabel = "abort"; // terminate this script error="abort"; OnComplete(); Cleanup (); } } if (type == actionType.queueScript){ // no script and loop set means flush all scripts from the queue if (scriptToExecute == null && loop && (stringParam2 == null || stringParam2 == "")){ // remove all scripts that are not currently on the stack from the queue executedBy.caller.FlushScriptQueue(); OnComplete(); Cleanup (); return; } if (scriptToExecute == null && stringParam2 != null && stringParam2 != ""){ // try finding the named game object and look for an interaction script there GameObject isGO = GameObject.Find(stringParam2); if (isGO != null) scriptToExecute = isGO.GetComponent<InteractionScript>(); } if (scriptToExecute != null) executedBy.QueueScript(scriptToExecute, executedBy.ResolveArgs(stringParam)+" trigger="+name, objectToAffect, ease); else Debug.LogError("FAILED TO FIND script named \""+stringParam2+"\""); OnComplete(); Cleanup (); return; } if (type == actionType.wait){ // we ignore wait for completion on this one... // set the HoldPosition flag if requested if (loop){ NavMeshAgentWrapper w = objectToAffect.GetComponent<NavMeshAgentWrapper>(); if (w != null) w.HoldPosition(true); // if there is no condition, holdPosition will stick till the next character task } // specifying wait 0 and delay = #delay lets you pass a delay into the script. if (fadeLength==0 && stringParam.ToLower().Contains("delay=")){ string delayString = SubstituteArgsAndAttributes(stringParam); if (!float.TryParse(delayString.Replace("delay=",""),out fadeLength)){ Debug.LogWarning("bad delay time in scripted action "+ name + stringParam); OnComplete(); Cleanup (); } else { StartCoroutine(CompleteAfterDelay (fadeLength)); return; } } // let's see about waiting for a TAG:NAME if (stringParam.Contains(":") && !stringParam.Contains ("=")){ // this could be better at excluding other things that contain ":" // assume this thing is a tag, and post a listener //GUIManager.GetInstance().AddInteractCallback(null,myInteractCallback); Brain.GetInstance().AddCallback(myInteractCallback); // fadelength should be a timeout here if > 0 if (fadeLength > 0) StartCoroutine(CompleteAfterDelay (fadeLength)); } else { if (stringParam == "" || stringParam == null){ StartCoroutine(CompleteAfterDelay (fadeLength)); } else { waitingForCondition = true; conditionNode = BinaryExpressionNode.BuildTree(stringParam); if (fadeLength > 0) StartCoroutine(CompleteAfterDelay (fadeLength)); // this starts a timeout } } } if (type == actionType.characterTask){ // taskChar = objectToAffect.GetComponent<TaskCharacter>(); nmaWrapper = objectToAffect.GetComponent<NavMeshAgentWrapper>(); if (taskChar != null){ taskChar.Init(); // clears flags taskChar.executingScript = this; // restore this flag // overload 'ease' for random pathnode/animation if (moveToName.ToLower()=="random"){ ease=true; moveToName = SceneNode.GetRandomUnlockedNode().name; // this could return a null, BOOM! } else { ease=false; } StartCoroutine(CharacterTaskAfterDelay(fadeLength)); if (!waitForCompletion){ runIndependentUpdates = true; OnComplete (); } } } if (type == actionType.attach){ // TaskCharacter tc = objectToAffect.GetComponent<TaskCharacter>(); if (negate){ // this is a detach, which leaves the object loose at the top level of the hierarchy. if (tc != null){ tc.Detach(SubstituteArgsAndAttributes(attachmentOverride)); } } else { // this is an attach, and it's usually better to attach to a new parent than to just detach. bool attachingToTcBone = true; if (tc != null){ // if there's an attachment override, and you can find the object and a bone, // then place the object at the bone plus offset location string substituted = attachmentOverride; if (attachmentOverride != "" && attachmentOverride.Contains(" ")){ string[]p = attachmentOverride.Split (' '); GameObject targetObject = GameObject.Find (SubstituteArgsAndAttributes(p[0]).Replace ("\"","")); Transform parentBone = tc.GetComponent<AnimationManager>().GetBone(p[1].Replace ("\"","")); attachingToTcBone = (parentBone != null); if (targetObject == null){ Debug.LogError(executedBy.name+": "+name+" Script Attachment found no target object in "+attachmentOverride); OnComplete(); Cleanup (); return; } if (!attachingToTcBone){ // name is not a bone, see if there's a game object by this name GameObject parentObject = GameObject.Find (SubstituteArgsAndAttributes(p[1]).Replace ("\"","")); if (parentObject != null) parentBone = parentObject.transform; tc.Detach(targetObject.name); // remove this from the attached Objects list... } substituted = targetObject.name+" "+p[1].Replace ("\"",""); if (offset != new Vector3(-1,-1,-1)){ if (targetObject != null && parentBone != null){ // if there's a delay, then we can do the lerp in a co-routine if (fadeLength > 0){ StartCoroutine (AttachAfterDelay(targetObject,parentBone,tc,substituted,attachingToTcBone)); return; // don't cleanup or complete until after delayed lerp } else { targetObject.transform.position = parentBone.TransformPoint(offset);//position+offset; targetObject.transform.rotation = parentBone.rotation*Quaternion.Euler(orientation); if (!attachingToTcBone) targetObject.transform.parent = parentBone; } } } else { // performing attach using current position if (!attachingToTcBone) targetObject.transform.parent = parentBone; } } if (attachingToTcBone) tc.Attach(substituted); } } OnComplete(); Cleanup (); } if (type == actionType.spawn){ GameObject newObject = Instantiate(Resources.Load(stringParam), objectToAffect.transform.position, objectToAffect.transform.rotation) as GameObject; newObject.name = SubstituteArgsAndAttributes(stringParam2); if (stringParam3 != ""){ GameObject newParent = GameObject.Find (stringParam3); if (newParent != null){ newObject.transform.parent = newParent.transform; newObject.transform.localPosition = offset; } } executedBy.args["spawnedname"]=newObject.name; OnComplete(); Cleanup (); } if (type == actionType.destroy){ Destroy(objectToAffect); OnComplete(); Cleanup (); } if (type == actionType.unityMessage){ // if (objectToAffect != null) objectToAffect.SendMessage(stringParam,stringParam2); OnComplete(); Cleanup (); } if (type == actionType.lockPosition){ if (negate){ NavMeshAgentWrapper w = objectToAffect.GetComponent<NavMeshAgentWrapper>(); if (w != null) w.LockPosition(false); ScriptedObject so = objectToAffect.GetComponent<ScriptedObject>(); if (so != null) so.executePriorityLock = -1; } else { NavMeshAgentWrapper w = objectToAffect.GetComponent<NavMeshAgentWrapper>(); if (w != null) w.LockPosition(true); if (stringParam != ""){ int lockPriority; if (int.TryParse(stringParam,out lockPriority)){ ScriptedObject so = objectToAffect.GetComponent<ScriptedObject>(); if (so != null) so.executePriorityLock = lockPriority; } } // test unlocking any nodes we have locked, so they are not blocking. // this is specifically for BVM, but might be good overall. SceneNode.UnlockLocation(objectToAffect.transform.position,0.5f); // radius is completely arbitrary 0.44f is probably a good value. } OnComplete(); Cleanup (); } if (type == actionType.goToLine){ // executedBy.nextLineLabel = stringParam; // untested, and very scary OnComplete(); Cleanup (); } if (type == actionType.setIKTarget){ // TaskCharacter tc = objectToAffect.GetComponent<TaskCharacter>(); if (tc != null){ IKArmController ctlr = tc.IKArmRight; if (stringParam.ToLower().Contains ("left")) ctlr = tc.IKArmLeft; if ((moveToName == null) || moveToName == ""){ // we are clearing the target ctlr.target = null; } else { GameObject targetGo = GameObject.Find(moveToName); if (targetGo != null){ ctlr.target = targetGo.transform; HandPoser poser = targetGo.GetComponent<HandPoser>(); if (poser != null) poser.Setup(ctlr.hand); } } ctlr.blendTime = fadeLength; ctlr.offset = offset; ctlr.orientation = Quaternion.Euler(orientation); if (stringParam2 == null || stringParam2 == "") stringParam2 = "0"; float releaseTime = 0; float.TryParse(stringParam2, out releaseTime); ctlr.releaseTime = releaseTime; } OnComplete(); // we'll worry about wait for completion later TODO Cleanup (); } }
void AddScript(ScriptedObject so,string newName){ // create a new child game object with a default scripted action and link it in GameObject newChild = new GameObject(newName); InteractionScript newIS = newChild.AddComponent("InteractionScript") as InteractionScript; // maybe initialize some fields to meaningful defaults ? newIS.item = newName; newIS.triggerStrings = new string[1]; newIS.triggerStrings[0] = newName; newIS.triggerOnStatus = false; newIS.scriptLines = new ScriptedAction[0]; newChild.transform.parent = so.transform; if (so.scripts == null) so.scripts = new InteractionScript[0]; InteractionScript[] tmp = new InteractionScript[ so.scripts.Length]; for (int i=0; i < so.scripts.Length; i++){ tmp[i]= so.scripts[i]; } so.scripts = new InteractionScript[tmp.Length+1]; for (int i=0; i < tmp.Length; i++){ so.scripts[i] = tmp[i]; } so.scripts[tmp.Length] = newIS; EditorUtility.SetDirty(newIS); // go ahead and bring it up in the editor ScriptViewWindow.Init(newIS); }
public void ForceExecute(InteractionScript callingScript){ forceExecute = true; Execute(callingScript); }
// routine to pause execution of this script line until the debugger says to continue or step // the script editor will clear this flag when a button is pressed. IEnumerator WaitForDebugger(InteractionScript script){ while (script.waitingForDebugger){ yield return new WaitForSeconds(1); } }
public void ShowInspectorGUI(string GUIlabel){ // should probably return the dirty bit from here... // lets extend this, to show only the fields required by the selected action type. // that will make it a lot friendlier in the editor if (serializedObject == null) serializedObject = new SerializedObject(this); EditorGUI.BeginChangeCheck(); type = (actionType)EditorGUILayout.EnumPopup("Action type",(System.Enum)type); if (type == actionType.enableInteraction){ objectToAffect = (GameObject)EditorGUILayout.ObjectField("objectToAffect",objectToAffect,typeof(GameObject),true); if (objectName == null) objectName = ""; objectName = EditorGUILayout.TextField("objectName",objectName); stringParam = EditorGUILayout.TextField("InteractionTAG",stringParam);// used for a lot of different things negate = EditorGUILayout.Toggle("disable",negate); // use to turn enable to disable, stop audio, etc. loop = EditorGUILayout.Toggle("append",loop); texture2D = (Texture2D)EditorGUILayout.ObjectField("iconTexture",texture2D,typeof(Texture2D),true); ease = EditorGUILayout.Toggle("remove icon",ease); // hackfully abuse this boolean } if (type == actionType.playAudio){ objectToAffect = (GameObject)EditorGUILayout.ObjectField("objectToPlay",objectToAffect,typeof(GameObject),true); if (objectName == null) objectName = ""; objectName = EditorGUILayout.TextField("objectName",objectName); if (stringParam == null) stringParam = ""; stringParam = EditorGUILayout.TextField("MappedSoundName",stringParam);// used for a lot of different things audioClip = (AudioClip)EditorGUILayout.ObjectField("audioClip",audioClip,typeof(AudioClip),true); fadeLength = EditorGUILayout.FloatField("delay After",fadeLength); if (stringParam2 == null) stringParam2 = ""; stringParam2 = EditorGUILayout.TextField("LookAt",stringParam2); // fadeLength = EditorGUILayout.FloatField("fadeLength",fadeLength); // also used for wait, move // ease = EditorGUILayout.Toggle("ease",ease); // ease or linear movement/fade negate = EditorGUILayout.Toggle("stop",negate); // use to turn enable to disable, stop audio, etc. loop = EditorGUILayout.Toggle("loop",loop); } if (type == actionType.playAnimation){ objectToAffect = (GameObject)EditorGUILayout.ObjectField("objectToAnimate",objectToAffect,typeof(GameObject),true); if (objectName == null) objectName = ""; objectName = EditorGUILayout.TextField("objectName",objectName); if (stringParam == null) stringParam = ""; stringParam = EditorGUILayout.TextField("animation",stringParam);// used for a lot of different things if (eventScript == null) eventScript = ""; eventScript = EditorGUILayout.TextField("eventScript",eventScript); // fadeLength = EditorGUILayout.FloatField("fadeLength",fadeLength); // also used for wait, move // desiredAlpha = EditorGUILayout.FloatField("desiredAlpha",desiredAlpha); loop = EditorGUILayout.Toggle("loop",loop); } if (type == actionType.putMessage){ objectToAffect = (GameObject)EditorGUILayout.ObjectField("objectToAffect",objectToAffect,typeof(GameObject),true); if (objectName == null) objectName = ""; objectName = EditorGUILayout.TextField("objectName",objectName); fadeLength = EditorGUILayout.FloatField("delay",fadeLength); // see about adding local gameMessage to use in this script if (gameMsgForm == null){ gameMsgForm = gameObject.AddComponent<GameMsgForm>();//gameObject.AddComponent<GameMsgForm>(); // could just do this when we know we'll need one... gameMsgForm.map = gameObject.AddComponent<InteractionMapForm>(); //gameObject.AddComponent<InteractionMapForm>(); EditorUtility.SetDirty(this); } else { if (gameMsgForm.ShowInspectorGUI()) EditorUtility.SetDirty(this); } if (gameMsgForm.msgType==GameMsgForm.eMsgType.dialogMsg) dialogIfThen = EditorGUILayout.Toggle("Treat As If-Then-Else",dialogIfThen); // stringParam = EditorGUILayout.TextField("message tag",stringParam);// used for a lot of different things } if (type == actionType.move){ objectToAffect = (GameObject)EditorGUILayout.ObjectField("objectToMove",objectToAffect,typeof(GameObject),true); if (objectName == null) objectName = ""; objectName = EditorGUILayout.TextField("objectName",objectName); fadeLength = EditorGUILayout.FloatField("moveTime",fadeLength); // also used for wait, move moveTo = (Transform)EditorGUILayout.ObjectField("moveTo",moveTo,typeof(Transform),true); if (moveToName == null) moveToName = ""; moveToName = EditorGUILayout.TextField("moveToName",moveToName); offset = EditorGUILayout.Vector3Field("offset",offset); // in moveTo reference frame ease = EditorGUILayout.Toggle("ease",ease); // ease or linear movement/fade } if (type == actionType.fade){ objectToAffect = (GameObject)EditorGUILayout.ObjectField("objectToAffect",objectToAffect,typeof(GameObject),true); if (objectName == null) objectName = ""; objectName = EditorGUILayout.TextField("objectName",objectName); // stringParam = EditorGUILayout.TextField("stringParam",stringParam);// used for a lot of different things fadeLength = EditorGUILayout.FloatField("fadeLength",fadeLength); // also used for wait, move desiredAlpha = EditorGUILayout.FloatField("desiredAlpha",desiredAlpha); desiredColor = EditorGUILayout.ColorField("desiredColor",desiredColor); if (stringParam == null) stringParam = ""; stringParam = EditorGUILayout.TextField("New Matl or Mesh",stringParam); ease = EditorGUILayout.Toggle("ease",ease); // ease or linear movement/fade } if (type == actionType.ifThenElse){ objectToAffect = (GameObject)EditorGUILayout.ObjectField("objectToTest",objectToAffect,typeof(GameObject),true); if (objectName == null) objectName = ""; objectName = EditorGUILayout.TextField("objectName",objectName); if (stringParam == null) stringParam = ""; stringParam = ValidateConditionalString("attribute conditional",stringParam);// used for a lot of different things } if (type == actionType.executeScript){ objectToAffect = (GameObject)EditorGUILayout.ObjectField("objectToExecute",objectToAffect,typeof(GameObject),true); if (objectName == null) objectName = ""; objectName = EditorGUILayout.TextField("objectName",objectName); scriptToExecute = (InteractionScript)EditorGUILayout.ObjectField("scriptToExecute",scriptToExecute,typeof(InteractionScript),true); if (scriptToExecute != null) stringParam2 = scriptToExecute.name; if (stringParam2 == null) stringParam2 = ""; stringParam2 = EditorGUILayout.TextField("script name",stringParam2); if (stringParam == null) stringParam = ""; stringParam = EditorGUILayout.TextField("args",stringParam);// used for a lot of different things ease = EditorGUILayout.Toggle("pass args",ease); // reused boolean } if (type == actionType.queueScript){ objectToAffect = (GameObject)EditorGUILayout.ObjectField("objectToExecute",objectToAffect,typeof(GameObject),true); if (objectName == null) objectName = ""; objectName = EditorGUILayout.TextField("objectName",objectName); scriptToExecute = (InteractionScript)EditorGUILayout.ObjectField("scriptToExecute",scriptToExecute,typeof(InteractionScript),true); if (scriptToExecute != null) stringParam2 = scriptToExecute.name; if (stringParam2 == null) stringParam2 = ""; stringParam2 = EditorGUILayout.TextField("script name",stringParam2); if (stringParam == null) stringParam = ""; stringParam = EditorGUILayout.TextField("args",stringParam);// used for a lot of different things ease = EditorGUILayout.Toggle("pass args",ease); // reused boolean loop = EditorGUILayout.Toggle("check to flush",loop); // reused boolean if (loop) stringParam2 = ""; //flush takes empty script } if (type == actionType.wait){ if (stringParam == null) stringParam = ""; stringParam = ValidateConditionalString("wait Condition",stringParam); if (stringParam != "" && stringParam != null) fadeLength = EditorGUILayout.FloatField("Timeout Value",fadeLength); else fadeLength = EditorGUILayout.FloatField("wait Time",fadeLength); // also used for wait, move if (preAttributes!="" || postAttributes != "" || stringParam != ""){ objectToAffect = (GameObject)EditorGUILayout.ObjectField("object for Attributes",objectToAffect,typeof(GameObject),true); if (objectName == null) objectName = ""; objectName = EditorGUILayout.TextField("object Name for attributes",objectName); } loop = EditorGUILayout.Toggle("Hold Position",loop); // reused boolean } if (type == actionType.characterTask){ objectToAffect = (GameObject)EditorGUILayout.ObjectField("characterToAffect",objectToAffect,typeof(GameObject),true); if (objectName == null) objectName = ""; objectName = EditorGUILayout.TextField("characterName",objectName); if (moveToName == null) moveToName = ""; moveToName = EditorGUILayout.TextField("Position",moveToName);// used for a lot of different things if (stringParam == null) stringParam = ""; stringParam = EditorGUILayout.TextField("Posture",stringParam); if (stringParam2 == null) stringParam2 = ""; stringParam2 = EditorGUILayout.TextField("LookAt",stringParam2); if (stringParam3 == null) stringParam3 = ""; stringParam3 = EditorGUILayout.TextField("Animation",stringParam3); fadeLength = EditorGUILayout.FloatField("delay",fadeLength); if (voiceTag == null) voiceTag = ""; voiceTag = EditorGUILayout.TextField("voiceTag",voiceTag); if (stringParam4 == null) stringParam4 = ""; stringParam4 = EditorGUILayout.TextField(":COMPLETE msg?",stringParam4); heading = EditorGUILayout.FloatField("Heading",heading); speed = EditorGUILayout.FloatField ("Speed",speed); if (attachmentOverride == null) attachmentOverride = ""; attachmentOverride = EditorGUILayout.TextField("attachmentOverride",attachmentOverride); if (eventScript == null) eventScript = ""; eventScript = EditorGUILayout.TextField("eventScript",eventScript); // I had no idea how to write this, but thanks to Unity forums, here is a nice Array custom inspector! serializedObject.Update(); EditorGUIUtility.LookLikeInspector(); SerializedProperty myIterator = serializedObject.FindProperty("syncToTasks"); while (true){ Rect myRect = GUILayoutUtility.GetRect(0f, 16f); bool showChildren = EditorGUI.PropertyField(myRect, myIterator); if (!myIterator.NextVisible(showChildren)) break; } serializedObject.ApplyModifiedProperties() ; EditorGUIUtility.LookLikeControls(); // end of Thanks to the Forums for the code! } if (type == actionType.attach){ negate = EditorGUILayout.Toggle("check for DETACH",negate); objectToAffect = (GameObject)EditorGUILayout.ObjectField("objectToAffect",objectToAffect,typeof(GameObject),true); if (objectName == null) objectName = ""; objectName = EditorGUILayout.TextField("objectName",objectName); if (attachmentOverride == null) attachmentOverride = ""; if (negate) attachmentOverride = EditorGUILayout.TextField("reparentOverride",attachmentOverride); else attachmentOverride = EditorGUILayout.TextField("target parent Override",attachmentOverride); offset = EditorGUILayout.Vector3Field("offset",offset); orientation = EditorGUILayout.Vector3Field("orientation",orientation); fadeLength = EditorGUILayout.FloatField("lerpTime",fadeLength); // stringParam = EditorGUILayout.TextField("parent name",stringParam);// used for a lot of different things } if (type == actionType.spawn){ objectToAffect = (GameObject)EditorGUILayout.ObjectField("SpawnLocationObject",objectToAffect,typeof(GameObject),true); if (objectName == null) objectName = ""; objectName = EditorGUILayout.TextField("LocationObjectName",objectName); if (stringParam == null) stringParam = ""; stringParam = EditorGUILayout.TextField("template",stringParam);// used for a lot of different things if (stringParam2 == null) stringParam2 = ""; stringParam2 = EditorGUILayout.TextField("newName",stringParam2); if (stringParam3 == null) stringParam3 = ""; stringParam3 = EditorGUILayout.TextField("newParent?",stringParam3); // loop = EditorGUILayout.Toggle("attach To Location?",loop); offset = EditorGUILayout.Vector3Field("attach offset",offset); } if (type == actionType.destroy){ objectToAffect = (GameObject)EditorGUILayout.ObjectField("objectToAffect",objectToAffect,typeof(GameObject),true); if (objectName == null) objectName = ""; objectName = EditorGUILayout.TextField("objectName",objectName); } if (type == actionType.unityMessage){ objectToAffect = (GameObject)EditorGUILayout.ObjectField("objectToAnimate",objectToAffect,typeof(GameObject),true); if (objectName == null) objectName = ""; objectName = EditorGUILayout.TextField("objectName",objectName); if (stringParam == null) stringParam = ""; stringParam = EditorGUILayout.TextField("method",stringParam);// used for a lot of different things if (stringParam2 == null) stringParam2 = ""; stringParam2 = EditorGUILayout.TextField("argumentString",stringParam2);// used for a lot of different things } if (type == actionType.lockPosition){ objectToAffect = (GameObject)EditorGUILayout.ObjectField("objectToLock",objectToAffect,typeof(GameObject),true); if (objectName == null) objectName = ""; objectName = EditorGUILayout.TextField("objectName",objectName); if (stringParam == null) stringParam = ""; stringParam = EditorGUILayout.TextField("lockScriptPriority",stringParam);// used for a lot of different things negate = EditorGUILayout.Toggle("check for UNLOCK",negate); } if (type == actionType.goToLine){ if (stringParam == null) stringParam = ""; stringParam = EditorGUILayout.TextField("abort or line#",stringParam); GUILayout.Label("BE CAREFUL WITH THOSE LINE NUMBERS!"); } if (type == actionType.setIKTarget){ objectToAffect = (GameObject)EditorGUILayout.ObjectField("taskCharacter",objectToAffect,typeof(GameObject),true); if (objectName == null) objectName = ""; objectName = EditorGUILayout.TextField("taskCharacterName",objectName); if (moveToName == null) moveToName = ""; moveToName = EditorGUILayout.TextField("targetName",moveToName);// used for a lot of different things if (stringParam == null) stringParam = ""; stringParam = EditorGUILayout.TextField("Left or Right",stringParam); fadeLength = EditorGUILayout.FloatField("blendTime",fadeLength); offset = EditorGUILayout.Vector3Field("offset",offset); orientation = EditorGUILayout.Vector3Field("orientation",orientation); if (stringParam2 == null) stringParam2 = "0"; stringParam2 = EditorGUILayout.TextField("Hold Time",stringParam2); } GUILayout.Space(10); if (comment == null) comment = ""; comment = EditorGUILayout.TextField("comment",comment); if (preAttributes == null) preAttributes = ""; preAttributes = EditorGUILayout.TextField("preAttributes",preAttributes); // set when line starts if (postAttributes == null) postAttributes = ""; postAttributes = EditorGUILayout.TextField("postAttributes",postAttributes); // set when line completes block = (blockType)EditorGUILayout.EnumPopup("IfThenElse bracket",(System.Enum)block); SetNamePrefix(block); executeOnlyOnce = EditorGUILayout.Toggle("executeOnlyOnce",executeOnlyOnce); waitForCompletion = EditorGUILayout.Toggle("waitForCompletion",waitForCompletion); sequenceEnd = EditorGUILayout.Toggle("sequenceEnd",sequenceEnd); breakpoint = EditorGUILayout.Toggle("debug breakpoint",breakpoint); bool dirty = EditorGUI.EndChangeCheck(); if (dirty){ if (objectToAffect != null && objectName == ""){ // default, or we could try looking up the name again... objectName = objectToAffect.name; } if (moveTo != null && moveToName == ""){ // default, or we could try looking up the name again... moveToName = moveTo.name; } if (scriptToExecute != null && stringParam2 == ""){ // default, or we could try looking up the name again... stringParam2 = scriptToExecute.name; } EditorUtility.SetDirty(this); } /* cut and paste reference for new inspector types * objectToAffect = (GameObject)EditorGUILayout.ObjectField("objectToAffect",objectToAffect,typeof(GameObject)); objectName = EditorGUILayout.TextField("objectName",objectName); stringParam = EditorGUILayout.TextField("stringParam",stringParam);// used for a lot of different things audioClip = (AudioClip)EditorGUILayout.ObjectField("audioClip",audioClip,typeof(AudioClip)); fadeLength = EditorGUILayout.FloatField("fadeLength",fadeLength); // also used for wait, move desiredAlpha = EditorGUILayout.FloatField("desiredAlpha",desiredAlpha); desiredColor = EditorGUILayout.ColorField("desiredColor",desiredColor); moveTo = (Transform)EditorGUILayout.ObjectField("moveTo",moveTo,typeof(Transform)); ease = EditorGUILayout.Toggle("ease",ease); // ease or linear movement/fade negate = EditorGUILayout.Toggle("negate",negate); // use to turn enable to disable, stop audio, etc. loop = EditorGUILayout.Toggle("loop",loop); waitForCompletion = EditorGUILayout.Toggle("waitForCompletion",waitForCompletion); executeOnlyOnce = EditorGUILayout.Toggle("executeOnlyOnce",executeOnlyOnce); ifBranch = EditorGUILayout.TextField("ifBranch",ifBranch); elseBranch = EditorGUILayout.TextField("elseBranch",elseBranch); */ /* if (GUILayout.Button("SERIALIZE")){ // ScriptedActionInfo info = ToInfo (this); ScriptedObject pop = this.transform.parent.parent.GetComponent<ScriptedObject>(); ScriptedObject.ScriptedObjectInfo info = pop.ToInfo (pop); XmlSerializer serializer = new XmlSerializer(typeof(ScriptedObject.ScriptedObjectInfo)); FileStream stream = new FileStream("TESTSOSERIAL.xml", FileMode.Create); serializer.Serialize(stream, info); stream.Close(); } */ }
public void NeededFor(InteractionScript script){ // if the calling script is higher priority than anyone already needing us, reserve us for that. if (reservedForScript == null || reservedForScript == script){ reservedForScript = script; return; } if (script.startPriority > reservedForScript.startPriority) reservedForScript = script; }
void Update() { //Debug.Log(keyForSafe); Debug.Log(key); RaycastHit hitInfo; Ray ray = Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0f)); Renderer currRenderer; if (Input.GetKey(KeyCode.G)) { key += 1; } UI_Key keys = GetComponent <UI_Key>(); if (Input.GetKey(KeyCode.P)) { keys.keyCount += 1; } // highlights gameObject if its a collectible and in range of raycast if (Physics.Raycast(ray.origin, ray.direction, out hitInfo, distanceToSee)) { if (hitInfo.transform.tag == "collectible" || hitInfo.transform.tag == "key") { // collect object and delete it from scene, adding +1 to inventory if (Input.GetKey(KeyCode.E)) { if (hitInfo.transform.tag == "key") { InteractionScript tresor = GetComponent <InteractionScript>(); tresor.safeKey = true; keyForSafe = true; Debug.LogFormat("Keys: {0} ", key); } if (hitInfo.transform.tag == "collectible") { collectable += 1; key += 1; Debug.LogFormat("collectibles: {0} ", collectable); } Destroy(hitInfo.collider.gameObject); } currRenderer = hitInfo.collider.gameObject.GetComponent <Renderer>(); if (currRenderer == renderer) { return; } if (currRenderer && currRenderer != renderer) { if (renderer) { renderer.sharedMaterial = originalMaterial; } } if (currRenderer) { renderer = currRenderer; } else { return; } originalMaterial = renderer.sharedMaterial; tempMaterial = new Material(originalMaterial); renderer.material = tempMaterial; renderer.material.color = highlightColor; } else { if (renderer) { renderer.sharedMaterial = originalMaterial; renderer = null; } } } }
public void ReleasedBy(InteractionScript script, ScriptedObject caller){ // Debug.LogError(name+" Released by "+script.name); if (reservedForScript == script) reservedForScript = null; // we cleared this when we started the script... if (actingInScript == script){ // if the releasing script was stacked, and will release to a higher script, we must not clear this // or it opens a window wher another waiting script could take control ScriptedObject so = caller; //GetComponent<ScriptedObject>(); if (so == null) so = GetComponent<ScriptedObject>(); if (so == null) return; if (so.scriptStack.Count <= 1){ // if the script that was running was not stacked // should we be setting this null here if we don't release ? // actingInScript = null; // now our character is free to run scripts. int checkCount = GetComponent<ScriptedObject>().scriptStack.Count; if (GetComponent<ScriptedObject>().scriptStack.Count == 0){ // or maybe 1 ? GetComponent<ScriptedObject>().ReleasedBy(script); actingInScript = null; // now our character is free to run scripts. } else { // what should this branch do ? GetComponent<ScriptedObject>().ReleasedBy(script); actingInScript = null; } } else{ ScriptedObject.QueuedScript temp = so.scriptStack.Pop (); InteractionScript callingScript = so.scriptStack.Peek ().script; so.scriptStack.Push (temp); // release any actors not needed by the calling script if (callingScript.actorObjects.Contains (this)){ actingInScript = callingScript; } else { // reenabled these two lines 11/19/15 to get queued blanket scripts to run in parallel actingInScript = null; GetComponent<ScriptedObject>().ReleasedBy(script); // this was added to fix leaving a hole when roll patient finished in exam bleeding // add me to the calling script's actors so i will be released when it is done // but maybe we shold fix exam bleeding by adding the needed characters instead // of this fix, which prevents actors from being released after sub scripts... //11/19/15 callingScript.actorObjects.Add (this); //11/19/15 actingInScript = callingScript; } } } }
public void InitFrom(ScriptedObjectInfo info){ // we should probably destroy any existing hierarchy here, calling OnDestroy() on our children; // initialize members from deserialized info gameObject.name = info.unityObjectName; moveToParentOnDrop = info.moveToParentOnDrop; // set this in each prefab, but false so constructed ones dont dropTargetName = info.dropTargetName; // make children from all the scriptInfos, and init each one from it's info, which will build the Actions scripts = new InteractionScript[info.scripts.Length]; for (int i = 0; i<info.scripts.Length; i++){ GameObject go = new GameObject(info.scripts[i].unityObjectName); go.transform.parent = this.transform; scripts[i] = go.AddComponent("InteractionScript") as InteractionScript; scripts[i].InitFrom(info.scripts[i]); } if (info.startupScriptName != null && info.startupScriptName != ""){ for (int i = 0; i<scripts.Length; i++){ if (scripts[i].name == info.startupScriptName){ startupScript = scripts[i]; break; } } } register = info.register; // instead, derive this from any contained scripts who listen to status messages prettyname = info.prettyname; // this was on the OI class, we shouldnt need it here XMLName = info.XMLName; XMLDirectory = info.XMLDirectory; assetBundleInfo = info.assetBundleInfo; voiceList = info.voiceList; voiceLists = info.voiceLists; vitalsBehaviors = info.vitalsBehaviors; scanRecords = info.scanRecords; }
// Start is called before the first frame update void Start() { interactionScript = player.GetComponent <InteractionScript>(); rotation = linkedDoor.transform.rotation.eulerAngles; rotation = new Vector3(rotation.x, rotation.y, rotation.z); }
public void QueueScript(InteractionScript script, string args, GameObject obj, int priority=0){ if (script == null){ Debug.LogError("Tried to queue null script - ignored"); return; } QueuedScript qs = new QueuedScript(); qs.script = script; qs.args = args; qs.obj = obj; qs.priority = priority; //Q scriptQueue.Enqueue(qs); scriptArray.Add (qs); qs.script.queueCount++; //Debug.Log (name+" queued "+qs.script.name+" after queuing, count is "+scriptArray.Count); // if (scriptArray.Count == 1){ if (myOI.actingInScript == null && scriptArray.Count == 1){ if (script.isReadyToRun(obj.GetComponent<BaseObject>(),true)){ qs.executing=true; ExecuteScript(script,args,obj,priority); } else { // verbalize an acknowledgement that the order has been recieved checkForScriptReady=true; } } else { // verbalize an acknowledgement that the order has been recieved // if the currently running script is cancellable, and its priority is lower than ours, // send it a cancel if (scriptStack.Count > 0){ QueuedScript qScr = scriptStack.Peek(); if (qScr != null && qScr.script.cancellable && qScr.priority < priority){ qScr.script.Cancel(); } } } }
public void PlayNext(float blendTime) { // there's something wrong about this scriptNameOverride logic. TODO Fix this! if (!scriptNameOverride) eventScript = null; // skip this one time if name was specified in interaction argument scriptNameOverride = false; if(animQueue.Count > 0) { currentAnim = animQueue.Dequeue().name; #if DEBUG_ANIM Debug.Log ("AM.PlayNext(" + this.name + ") : blendTime=" + blendTime + " : currentAnim=" + currentAnim + " : time=" + Time.time ); #endif if(currentAnim == baseClip.name) AnimState = CharacterAnimState.Idle; else idleEnabled = false; if (animTime == 0) // if a call has overridden start time, don't rewind body.animation.Rewind(currentAnim); animTime = 0; // only use once // if (animWeight == 1){ body.animation.CrossFade(currentAnim, blendTime); // } else { //blend also seems to mess up some event related stuff // body.animation.Blend(currentAnim,animWeight,blendTime); // this will leave the idle playing at 1-weight, we should blend it out. // } body.GetComponent<AnimationMessenger>().ExpectEventsFor(currentAnim); } else { ErrorAbort("PlayNext() animQueue == 0", blendTime); } }
public void OnScriptComplete(InteractionScript script,string error){ lastScriptExecuted = script; lastScriptExecutedTime = Time.time; //Debug.Log (name+" before dequeuing, count is "+scriptQueue.Count); // error might tell us this was aborted, how should we handle it ? abort the whole stack ? possibly. // QueuedScript completedScript = if (scriptStack.Count > 0) scriptStack.Pop(); // if there is anything still on the stack, updates will start giong to it, if (scriptStack.Count > 0) return; // if the stack is empty, see if there is a queued script waiting to be executed... //Q QueuedScript dequeuedScript = scriptQueue.Dequeue(); foreach (object obj in scriptArray){ if ((obj as QueuedScript).executing){ currentScript = null; script.queueCount--; scriptArray.Remove(obj); break; } } // scriptArray.Remove(currentScript); // we could remove this when we start it running instead of here... if (scriptArray.Count > 0){ // here is where we get intelligent about what to do next...for all the queued scripts, find the highest priority one which is ready to run right now. // if there isn't one, schedule update to keep checking until there is. //QueuedScript qs = scriptQueue.Peek(); QueuedScript qs = FindBestScript(); //scriptArray[0] as QueuedScript; // pick the highest priority ready to run script in the queue... if (qs != null){ qs.executing = true; ExecuteScript(qs.script,qs.args,qs.obj); } else { checkForScriptReady=true; } } }
public void DropCarryItem() { m_carryItem = null; }
// some utilities to help editor tools manage the scripts list public int IndexOf(InteractionScript script){ int index=-1; for (int i=0;i<scripts.Length;i++){ if (scripts[i] == script){ index = i; break; } } return index; }
void OnGUI(){ if (confirmChange){ GUILayout.Label("EXIT WITHOUT SAVING CHANGES?"); if (GUILayout.Button("YES, EXIT")){ myScript = requestedScript; confirmChange = false; Init (myScript); } if (GUILayout.Button("NO! SAVE!")){ myParent.SaveToXML(myParent.XMLName); hasChanged = false; myScript = requestedScript; confirmChange = false; Init (myScript); } return; } if (Application.isPlaying) hasBeenRunning = true; if (myScript != null && hasLostScript){ // we've gotten our instance back, reinitialize. if (myParent != null){ InteractionScript reconnectInstance = null; reconnectInstance = EditorUtility.InstanceIDToObject(scriptInstanceID) as InteractionScript; if (reconnectInstance != null){ Init (reconnectInstance); hasLostScript = false; } } //Init (myScript); // this reconnected with a stale instance //hasLostScript = false; return; } if (myScript== null || myScript.scriptLines == null){ GUILayout.Label("I lost my Script when we stopped running... what was it ?"); hasLostScript = true; return; } GUI.color = Color.white; GUILayout.BeginHorizontal(); string pName = "NO ScriptedObject"; if (myParent != null){ pName = myParent.name; GUILayout.Label ("EDITING "+pName+"->"+myScript.name,GUILayout.ExpandWidth(false)); if (myScript.waitingForDebugger){ if (GUILayout.Button ("STEP",GUILayout.ExpandWidth(false))){ myScript.singleStepping = true; myScript.waitingForDebugger = false; } if (GUILayout.Button ("RUN to Break",GUILayout.ExpandWidth(false))){ myScript.singleStepping = false; myScript.waitingForDebugger = false; } if (Time.timeScale == 1.0){ if (GUILayout.Button ("1/10X",GUILayout.ExpandWidth(false))){ Time.timeScale = 0.1f; } } else { if (GUILayout.Button ("1X",GUILayout.ExpandWidth(false))){ Time.timeScale = 1.0f; } } } myScript.debug = GUILayout.Toggle(myScript.debug,"dbg",GUILayout.ExpandWidth(false)); if (AnyBreakpoints() && GUILayout.Button("-bkpts",GUILayout.ExpandWidth(false))) ClearAllBreakpoints(); if (hasChanged && !hasBeenRunning){ if (GUILayout.Button ("SAVE to",GUILayout.ExpandWidth(false))){ myParent.SaveToXML(myParent.XMLName); hasChanged = false; ignoreChangeOnce = true; } myParent.XMLName = GUILayout.TextField (myParent.XMLName); } else { if (GUILayout.Button ("UNCHANGED (SAVE)",GUILayout.ExpandWidth(false))){ myParent.SaveToXML(myParent.XMLName); hasChanged = false; ignoreChangeOnce = true; } if (myParent != null){ if (myParent.XMLName == null) myParent.XMLName = ""; myParent.XMLName = GUILayout.TextField (myParent.XMLName); // keep the same number of controls ? } } } GUILayout.EndHorizontal(); scrollPos = EditorGUILayout.BeginScrollView(scrollPos); indent = ""; // prevent runaway! for (int i=0; i< myScript.scriptLines.Length; i++){ if (confirmDelete == i){ GUILayout.Label("CONFIRM you want to delete this line? Cannot UNDO (yet)!"); if (GUILayout.Button("YES, DELETE FOREVER!")){ myScript.DeleteLineAt(i); hasChanged = true; confirmDelete = -1; } if (GUILayout.Button("Umm, no, sorry, I didn't mean it. Keep the line")){ confirmDelete = -1; ignoreChangeOnce = true; } } bool expand = false; GUILayout.BeginHorizontal(); GUI.backgroundColor = Color.grey; if (GUILayout.Button (new GUIContent("X",null,"delete line"),GUILayout.ExpandWidth(false))){ // myScript.DeleteLineAt(i); // hasChanged = true; confirmDelete = i; ignoreChangeOnce = true; break; // we've affected the array, don't draw any more gui this frame. } if (GUILayout.Button (new GUIContent("+",null,"insert line before"),GUILayout.ExpandWidth(false))){ myScript.InsertLineAt(i); hasChanged=true; break; } if (Selection.activeObject != myScript.scriptLines[i].gameObject){ GUI.backgroundColor = Color.yellow; if (GUILayout.Button (new GUIContent(">",null,"EDIT line"),GUILayout.ExpandWidth(false))){ Selection.activeGameObject = myScript.scriptLines[i].gameObject; // Clear keyboard focus to get around text field value retention bug in unity GUIUtility.keyboardControl = 0; ignoreChangeOnce = true; } } else { GUI.backgroundColor = Color.red; expand = true; if (GUILayout.Button (new GUIContent("V",null,"CLOSE line"),GUILayout.ExpandWidth(false))){ Selection.activeGameObject = myScript.gameObject; ignoreChangeOnce = true; } } string prefix = i<10?" ":""; PreSetIndent(myScript.scriptLines[i]); if (myScript.scriptLines[i].hasExecuted) GUI.color = Color.yellow; if (myScript.readyState == InteractionScript.readiness.executing && myScript.currentLine == i) GUI.color = Color.green; GUILayout.Label(prefix+i+":"+indent+myScript.scriptLines[i].PrettyPrint(),GUILayout.Width(450)); GUI.color = Color.white; ShowFlowIcon(myScript.scriptLines[i]); PostSetIndent(myScript.scriptLines[i]); // if it's a noop, provide a copy from drop target if (myScript.scriptLines[i].type == ScriptedAction.actionType.wait && myScript.scriptLines[i].fadeLength == 0 && myScript.scriptLines[i].stringParam == "" && myScript.scriptLines[i].block == ScriptedAction.blockType.none){ // copy from dropped scriptedAction ScriptedAction droppedSA = null; droppedSA = (ScriptedAction)EditorGUILayout.ObjectField("CopyFrom",droppedSA,typeof(ScriptedAction),true,GUILayout.Width(200)); if (droppedSA != null){ ScriptedAction.ScriptedActionInfo info = droppedSA.ToInfo(droppedSA); myScript.scriptLines[i].InitFrom(info); } } if (GUILayout.Button (new GUIContent("?",null,"show help"),GUILayout.ExpandWidth(false))){ helpTarget = myScript.scriptLines[i]; ignoreChangeOnce = true; } GUILayout.EndHorizontal(); if (expand){ // if this is reliable, we may not need the change the current selection myScript.scriptLines[i].name = EditorGUILayout.TextField("name:",myScript.scriptLines[i].name); myScript.scriptLines[i].ShowInspectorGUI(""); } } if (indent != ""){ GUI.color = Color.red; GUILayout.Label ("WARNING: Unbalanced {} - Missing END }"); GUI.color = Color.white; } GUI.backgroundColor = Color.grey; if (GUILayout.Button ("+",GUILayout.ExpandWidth(false))){ myScript.InsertLineAt(myScript.scriptLines.Length); } EditorGUILayout.EndScrollView(); if (ignoreChangeOnce) { hasChanged = false; ignoreChangeOnce = false; } else { hasChanged |= GUI.changed; if (GUI.changed) EditorUtility.SetDirty(myScript); // see if this helps keep changes } ShowHelp(); }
// we could make this the main entry point to avoid overrun, and allow multi threading... public IEnumerator ExecuteWhenIdle(InteractionScript caller){ // this is kind of a failsafe in case scripts are written where no-wait overrun occurs. // initially, yield to allow the previous line to complete yield return new WaitForSeconds(0.01f); // if this is just sending a message, go ahead and do it if (type == actionType.putMessage){// maybe some other types as well... Execute (caller); return true; } while (taskChar.executingScript != null){ if (ignoreTimeout) yield break; if (executedBy.debug) Debug.Log (name+" waiting for idle "+taskChar.name+", still running "+taskChar.executingScript.name+" at "+Time.time); yield return new WaitForSeconds(0.5f); } taskChar.executingScript = this; // grab the character immediately Execute (caller); }
public void AppendFrom(ScriptedObjectInfo info){ // make children from all the scriptInfos, and init each one from it's info, which will build the Actions int hadScripts = scripts.Length; // append my scripts to the parent's ScriptedObject InteractionScript[] tmp = new InteractionScript[hadScripts]; for (int i = 0; i< hadScripts; i++) tmp[i] = scripts[i]; // since you can't extend an array, copy the old one here, create a new one, and copy back scripts = new InteractionScript[hadScripts + info.scripts.Length]; for (int i = 0; i< hadScripts; i++) scripts[i] = tmp[i]; for (int i = 0; i< info.scripts.Length; i++){ GameObject go = new GameObject(info.scripts[i].unityObjectName); go.transform.parent = this.transform; scripts[i+hadScripts] = go.AddComponent("InteractionScript") as InteractionScript; scripts[i+hadScripts].InitFrom(info.scripts[i]); } // see if there's a startup script to link if (info.startupScriptName != null && info.startupScriptName != ""){ for (int i = 0; i<scripts.Length; i++){ if (scripts[i].name == info.startupScriptName){ startupScript = scripts[i]; break; } } } }
public InteractionScriptInfo ToInfo(InteractionScript script){ // saves values to an info for serialization (to XML) InteractionScriptInfo info = new InteractionScriptInfo(); info.unityObjectName = script.name; info.triggerStrings = script.triggerStrings; // the string that causes this script to start running info.triggerOnStatus = script.triggerOnStatus; // should we listen to InteractStatusMessages for our trigger ? info.startingArgs = script.startingArgs; info.scriptLines = new ScriptedAction.ScriptedActionInfo[script.scriptLines.Length]; for (int i = 0; i<script.scriptLines.Length; i++){ if (script.scriptLines[i] != null){ info.scriptLines[i] = script.scriptLines[i].ToInfo(script.scriptLines[i]); } else { Debug.Log("Script "+script.name+"contains null line at index "+i); #if UNITY_EDITOR EditorUtility.DisplayDialog("Save Failed","Script "+script.name+"contains null line at index "+i,"OK"); #endif } } // public ScriptedAction.ScriptedActionInfo[] abortBranch; // the way out, if the user chooses not to complete this script // public ScriptedAction.ScriptedActionInfo[] errorBranch; // what to do if the script hangs, times out, encounters an error... info.owningRole = script.owningRole; if (script.roles != null) info.roles = new List<string>(script.roles); // if null, then just one role for this script info.roleKeyString = script.roleKeyString; // enter this as a string in the editor, it gets parsed into a node tree on awake. info.autoExecuteInterval = script.autoExecuteInterval; info.autoExecuteProbability = script.autoExecuteProbability; info.AddToMenu = script.AddToMenu; info.menuOrder = script.menuOrder; info.interactionSet = script.interactionSet; info.commandVariation = script.commandVariation; info.callbackConfirmVoice = script.callbackConfirmVoice; info.item = script.item; info.prettyname = script.prettyname; info.response = script.response; info.response_title = script.response_title; info.note = script.note; info.tooltip = script.tooltip; info.sound = script.sound; info.task = script.task; info.log = script.log; info.readyState = script.readyState; // since an object reference is required to calc this, no getter. info.startPriority = script.startPriority; // 0 is the lowest info.cancellable = script.cancellable; info.skillVector = script.skillVector; info.extraCost = script.extraCost; info.prereq = script.prereq; info.category = script.category; info.param = script.param; info.debug = false; // always clear this when serializing.// print out debug logging while running return info; }
public void ExecuteScript( InteractionScript script, string args, GameObject obj, int priority=0){ // this can be called from a scriptedInteraction if (script == null){ Debug.LogError("Tried to execute null script - ignored"); return; } QueuedScript qs = new QueuedScript(); qs.script = script; qs.args = args; qs.obj = obj; qs.priority = priority; scriptStack.Push(qs); currentScript = qs; if (scriptStack.Count > 1) Debug.Log (name+" stacked "+qs.script.name+" after stacking, count is "+scriptStack.Count); script.Execute(this,args,obj); // we always start a script when this is called }
public void ExecuteScript(InteractionScript script, string passedArgs, GameObject obj, bool passArgs){ // this is called by a scripted action, and gives us a chance to add our args to be passed into the called script if (passArgs){ foreach (KeyValuePair<string,string> pair in args){ if (pair.Value != ""){ passedArgs = pair.Key+"="+pair.Value+" "+passedArgs; } else { passedArgs = pair.Key+" "+passedArgs; } } } caller.ExecuteScript(script,passedArgs,obj); }
public void ReleasedBy(InteractionScript script){ // if we were running in someone elses script, we might need restart our own script queue // may need some conditional checking here. if (scriptArray.Count > 0){ // and nothing stacked ? checkForScriptReady = true; } }
public void QueueScript(InteractionScript script, string passedArgs, GameObject obj, bool passArgs){ // this is called by a scripted action, and gives us a chance to add our args to be passed into the called script if (passArgs){ foreach (KeyValuePair<string,string> pair in args){ if (pair.Value != ""){ passedArgs = pair.Key+"="+pair.Value+" "+passedArgs; } else { passedArgs = pair.Key+" "+passedArgs; } } } //TODO Are we putting this script onto the wrong object's queue ? If obj has a scripted object, shouldnt it go onto that queue ? ScriptedObject targetSO = obj.GetComponent<ScriptedObject>(); if (targetSO != null && targetSO != caller){ Debug.LogWarning("Check if intended behavior, queuing script"+script.name+" for other task character from "+this.name); targetSO.QueueScript(script,passedArgs,obj,script.startPriority); }else{ caller.QueueScript(script,passedArgs,obj,script.startPriority); // priority passing added 4/22/13 PAA } }
public void InsertScriptSorted(InteractionScript script){ int desiredIndex = script.menuOrder; //Find the slot where this menuOrder should be placed and insert there InsertScriptAt( script, desiredIndex); }
// Start is called before the first frame update void Start() { interactor = new InteractionScript(); //Making it so the cursor is not visible in the play area Cursor.lockState = CursorLockMode.Locked; }
public void RemoveScript(InteractionScript script){ // remove from array if found, but don't destroy or un-parent the script int index= IndexOf(script); if (index < 0) return; InteractionScript[] newScripts = new InteractionScript[scripts.Length-1]; for (int i=0; i<index; i++){ newScripts[i] = scripts[i]; } for (int i=index+1; i<scripts.Length; i++){ newScripts[i-1] = scripts[i]; } scripts = newScripts; }
public bool IsAvailableFor(InteractionScript script){ // NeededFor (script); // this should only be done when we actually queue a script for execution. // if we are idle and reserved for noone, or reserved for the caller, then true if (actingInScript != null) return false; // if locked because performing some operations (BVM, for example) // this fails, once locked, a character cannot become unlocked. re-think this. /* NavMeshAgentWrapper wrapper = GetComponent<NavMeshAgentWrapper>(); if (wrapper != null && (wrapper.lockPosition || wrapper.holdPosition)) return false; */ if (reservedForScript == null || reservedForScript == script) return true; return false; }