public override void OnInspectorGUI()
        {
            ActionListAsset _target = (ActionListAsset)target;

            ActionListAssetEditor.ShowPropertiesGUI(_target);
            EditorGUILayout.Space();

            EditorGUILayout.BeginHorizontal();
            if (GUILayout.Button("Expand all", EditorStyles.miniButtonLeft))
            {
                Undo.RecordObject(_target, "Expand actions");
                foreach (AC.Action action in _target.actions)
                {
                    action.isDisplayed = true;
                }
            }
            if (GUILayout.Button("Collapse all", EditorStyles.miniButtonMid))
            {
                Undo.RecordObject(_target, "Collapse actions");
                foreach (AC.Action action in _target.actions)
                {
                    action.isDisplayed = false;
                }
            }
            if (GUILayout.Button("Action List Editor", EditorStyles.miniButtonMid))
            {
                ActionListEditorWindow.Init(_target);
            }
            if (!Application.isPlaying)
            {
                GUI.enabled = false;
            }
            if (GUILayout.Button("Run now", EditorStyles.miniButtonRight))
            {
                if (KickStarter.actionListAssetManager != null)
                {
                    if (!_target.canRunMultipleInstances)
                    {
                        int numRemoved = KickStarter.actionListAssetManager.EndAssetList(_target);
                        if (numRemoved > 0)
                        {
                            ACDebug.Log("Removed 1 instance of ActionList asset '" + _target.name + "' because it is set to only run one at a time.", _target);
                        }
                    }

                    AdvGame.RunActionListAsset(_target);
                }
                else
                {
                    ACDebug.LogWarning("An AC PersistentEngine object must be present in the scene for ActionList assets to run.", _target);
                }
            }
            GUI.enabled = true;
            EditorGUILayout.EndHorizontal();
            EditorGUILayout.Space();

            if (actionsManager == null)
            {
                EditorGUILayout.HelpBox("An Actions Manager asset file must be assigned in the Game Editor Window", MessageType.Warning);
                OnEnable();
                return;
            }

            if (!actionsManager.displayActionsInInspector)
            {
                EditorGUILayout.HelpBox("As set by the Actions Manager, Actions are only displayed in the ActionList Editor window.", MessageType.Info);
                return;
            }

            for (int i = 0; i < _target.actions.Count; i++)
            {
                int typeIndex = KickStarter.actionsManager.GetActionTypeIndex(_target.actions[i]);

                if (_target.actions[i] == null)
                {
                    _target.actions.Insert(i, ActionListAssetEditor.RebuildAction(_target.actions[i], typeIndex, _target));
                }

                _target.actions[i].isAssetFile = true;

                EditorGUILayout.BeginVertical("Button");

                string actionLabel = " (" + i + ") " + actionsManager.GetActionTypeLabel(_target.actions[i], true);
                actionLabel = actionLabel.Replace("\r\n", "");
                actionLabel = actionLabel.Replace("\n", "");
                actionLabel = actionLabel.Replace("\r", "");
                if (actionLabel.Length > 40)
                {
                    actionLabel = actionLabel.Substring(0, 40) + "..)";
                }

                EditorGUILayout.BeginHorizontal();
                _target.actions[i].isDisplayed = EditorGUILayout.Foldout(_target.actions[i].isDisplayed, actionLabel);
                if (!_target.actions[i].isEnabled)
                {
                    EditorGUILayout.LabelField("DISABLED", EditorStyles.boldLabel, GUILayout.Width(100f));
                }

                if (GUILayout.Button("", CustomStyles.IconCog))
                {
                    ActionSideMenu(_target.actions[i]);
                }
                EditorGUILayout.EndHorizontal();

                if (_target.actions[i].isDisplayed)
                {
                    if (!actionsManager.DoesActionExist(_target.actions[i].GetType().ToString()))
                    {
                        EditorGUILayout.HelpBox("This Action type is not listed in the Actions Manager", MessageType.Warning);
                    }
                    else
                    {
                        int newTypeIndex = ActionListEditor.ShowTypePopup(_target.actions[i], typeIndex);
                        if (newTypeIndex >= 0)
                        {
                            // Rebuild constructor if Subclass and type string do not match
                            ActionEnd _end = new ActionEnd();
                            _end.resultAction   = _target.actions[i].endAction;
                            _end.skipAction     = _target.actions[i].skipAction;
                            _end.linkedAsset    = _target.actions[i].linkedAsset;
                            _end.linkedCutscene = _target.actions[i].linkedCutscene;

                            Undo.RecordObject(_target, "Change Action type");

                            _target.actions.Insert(i, ActionListAssetEditor.RebuildAction(_target.actions[i], newTypeIndex, _target, _end.resultAction, _end.skipAction, _end.linkedAsset, _end.linkedCutscene));
                        }

                        EditorGUILayout.Space();
                        GUI.enabled = _target.actions[i].isEnabled;

                        if (_target.useParameters)
                        {
                            if (Application.isPlaying)
                            {
                                _target.actions[i].AssignValues(_target.parameters);
                            }

                            _target.actions[i].ShowGUI(_target.parameters);
                        }
                        else
                        {
                            if (Application.isPlaying)
                            {
                                _target.actions[i].AssignValues(null);
                            }
                            _target.actions[i].ShowGUI(null);
                        }
                    }
                    GUI.enabled = true;
                }

                if (_target.actions[i].endAction == AC.ResultAction.Skip || _target.actions[i] is ActionCheck || _target.actions[i] is ActionCheckMultiple || _target.actions[i] is ActionParallel)
                {
                    _target.actions[i].SkipActionGUI(_target.actions, _target.actions[i].isDisplayed);
                }

                EditorGUILayout.EndVertical();
                EditorGUILayout.Space();
            }

            if (GUILayout.Button("Add new Action"))
            {
                Undo.RecordObject(_target, "Create action");
                AddAction(actionsManager.GetDefaultAction(), _target.actions.Count, _target);
            }

            if (GUI.changed)
            {
                EditorUtility.SetDirty(_target);
            }
        }
        private void Export()
        {
                        #if UNITY_WEBPLAYER
            ACDebug.LogWarning("Game text cannot be exported in WebPlayer mode - please switch platform and try again.");
                        #else
            if (variablesManager == null || exportColumns == null || exportColumns.Count == 0)
            {
                return;
            }

            bool canProceed = EditorUtility.DisplayDialog("Export variables", "AC will now go through your game, and collect all variables to be exported.\n\nIt is recommended to back up your project beforehand.", "OK", "Cancel");
            if (!canProceed)
            {
                return;
            }

            if (!UnityVersionHandler.SaveSceneIfUserWants())
            {
                return;
            }

            string suggestedFilename = "";
            if (AdvGame.GetReferences().settingsManager)
            {
                suggestedFilename = AdvGame.GetReferences().settingsManager.saveFileName + " - ";
            }
            suggestedFilename += "Variables.csv";

            string fileName = EditorUtility.SaveFilePanel("Export variables", "Assets", suggestedFilename, "csv");
            if (fileName.Length == 0)
            {
                return;
            }

            List <GVar> exportVars = new List <GVar>();
            foreach (GVar globalVariable in variablesManager.vars)
            {
                exportVars.Add(new GVar(globalVariable));
            }

            bool            fail   = false;
            List <string[]> output = new List <string[]>();

            List <string> headerList = new List <string>();
            headerList.Add("ID");
            foreach (ExportColumn exportColumn in exportColumns)
            {
                headerList.Add(exportColumn.GetHeader());
            }
            output.Add(headerList.ToArray());

            foreach (GVar exportVar in exportVars)
            {
                List <string> rowList = new List <string>();
                rowList.Add(exportVar.id.ToString());
                foreach (ExportColumn exportColumn in exportColumns)
                {
                    string cellText = exportColumn.GetCellText(exportVar, VariableLocation.Global);
                    rowList.Add(cellText);

                    if (cellText.Contains(CSVReader.csvDelimiter))
                    {
                        fail = true;
                        ACDebug.LogError("Cannot export variables since global variable " + exportVar.id.ToString() + " (" + exportVar.label + ") contains the character '" + CSVReader.csvDelimiter + "'.");
                    }
                }
                output.Add(rowList.ToArray());
            }

            // Local
            int      numLocalVars  = 0;
            string   originalScene = UnityVersionHandler.GetCurrentSceneFilepath();
            string[] sceneFiles    = AdvGame.GetSceneFiles();
            foreach (string sceneFile in sceneFiles)
            {
                UnityVersionHandler.OpenScene(sceneFile);

                List <GVar> localExportVars = new List <GVar>();
                if (FindObjectOfType <LocalVariables>())
                {
                    LocalVariables localVariables = FindObjectOfType <LocalVariables>();
                    string         sceneName      = UnityVersionHandler.GetCurrentSceneName();

                    foreach (GVar localVariable in localVariables.localVars)
                    {
                        localExportVars.Add(new GVar(localVariable));
                    }

                    foreach (GVar localExportVar in localExportVars)
                    {
                        numLocalVars++;

                        List <string> rowList = new List <string>();
                        rowList.Add(localExportVar.id.ToString());
                        foreach (ExportColumn exportColumn in exportColumns)
                        {
                            string cellText = exportColumn.GetCellText(localExportVar, VariableLocation.Local, sceneName);
                            rowList.Add(cellText);

                            if (cellText.Contains(CSVReader.csvDelimiter))
                            {
                                fail = true;
                                ACDebug.LogError("Cannot export variables since local variable " + localExportVar.id.ToString() + " (" + localExportVar.label + ") contains the character '" + CSVReader.csvDelimiter + "'.");
                            }
                        }
                        output.Add(rowList.ToArray());
                    }
                }
            }

            if (originalScene == "")
            {
                UnityVersionHandler.NewScene();
            }
            else
            {
                UnityVersionHandler.OpenScene(originalScene);
            }

            if (!fail)
            {
                int length = output.Count;

                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                for (int j = 0; j < length; j++)
                {
                    sb.AppendLine(string.Join(CSVReader.csvDelimiter, output[j]));
                }

                if (Serializer.SaveFile(fileName, sb.ToString()))
                {
                    ACDebug.Log((exportVars.Count - 1).ToString() + " global variables, " + numLocalVars.ToString() + " local variables exported.");
                }
            }

            //this.Close ();
                        #endif
        }
示例#3
0
        override public void ShowGUI(List <ActionParameter> parameters)
        {
            if (inventoryManager == null && AdvGame.GetReferences().inventoryManager)
            {
                inventoryManager = AdvGame.GetReferences().inventoryManager;
            }
            if (settingsManager == null && AdvGame.GetReferences().settingsManager)
            {
                settingsManager = AdvGame.GetReferences().settingsManager;
            }

            if (inventoryManager != null)
            {
                // Create a string List of the field's names (for the PopUp box)
                List <string> labelList = new List <string>();

                int i = 0;
                if (parameterID == -1)
                {
                    invNumber = -1;
                }

                if (inventoryManager.items.Count > 0)
                {
                    foreach (InvItem _item in inventoryManager.items)
                    {
                        labelList.Add(_item.label);

                        // If a item has been removed, make sure selected variable is still valid
                        if (_item.id == invID)
                        {
                            invNumber = i;
                        }
                        if (_item.id == invIDReplace)
                        {
                            replaceInvNumber = i;
                        }

                        i++;
                    }

                    if (invNumber == -1)
                    {
                        if (invID != 0)
                        {
                            ACDebug.Log("Previously chosen item no longer exists!");
                        }
                        invNumber = 0;
                        invID     = 0;
                    }

                    if (invAction == InvAction.Replace && replaceInvNumber == -1)
                    {
                        if (invIDReplace != 0)
                        {
                            ACDebug.Log("Previously chosen item no longer exists!");
                        }
                        replaceInvNumber = 0;
                        invIDReplace     = 0;
                    }

                    invAction = (InvAction)EditorGUILayout.EnumPopup("Method:", invAction);

                    string label = "Item to add:";
                    if (invAction == InvAction.Remove)
                    {
                        label = "Item to remove:";
                    }

                    parameterID = Action.ChooseParameterGUI(label, parameters, parameterID, ParameterType.InventoryItem);
                    if (parameterID >= 0)
                    {
                        invNumber = Mathf.Min(invNumber, inventoryManager.items.Count - 1);
                        invID     = -1;
                    }
                    else
                    {
                        invNumber = EditorGUILayout.Popup(label, invNumber, labelList.ToArray());
                        invID     = inventoryManager.items[invNumber].id;
                    }

                    if (inventoryManager.items[invNumber].canCarryMultiple)
                    {
                        setAmount = EditorGUILayout.Toggle("Set amount?", setAmount);

                        if (setAmount)
                        {
                            string _label = (invAction == InvAction.Remove) ? "Reduce count by:" : "Increase count by:";

                            amountParameterID = Action.ChooseParameterGUI(_label, parameters, amountParameterID, ParameterType.Integer);
                            if (amountParameterID < 0)
                            {
                                amount = EditorGUILayout.IntField(_label, amount);
                            }
                        }
                    }

                    if (invAction == InvAction.Replace)
                    {
                        replaceParameterID = Action.ChooseParameterGUI("Item to remove:", parameters, replaceParameterID, ParameterType.InventoryItem);
                        if (replaceParameterID >= 0)
                        {
                            replaceInvNumber = Mathf.Min(replaceInvNumber, inventoryManager.items.Count - 1);
                            invIDReplace     = -1;
                        }
                        else
                        {
                            replaceInvNumber = EditorGUILayout.Popup("Item to remove:", replaceInvNumber, labelList.ToArray());
                            invIDReplace     = inventoryManager.items[replaceInvNumber].id;
                        }
                    }
                    else if (invAction == InvAction.Add)
                    {
                        addToFront = EditorGUILayout.Toggle("Add to front?", addToFront);
                    }
                }
                else
                {
                    EditorGUILayout.HelpBox("No inventory items exist!", MessageType.Info);
                    invID            = -1;
                    invNumber        = -1;
                    invIDReplace     = -1;
                    replaceInvNumber = -1;
                }

                if (settingsManager != null && settingsManager.playerSwitching == PlayerSwitching.Allow && !settingsManager.shareInventory && invAction != InvAction.Replace)
                {
                    EditorGUILayout.Space();

                    setPlayer = EditorGUILayout.Toggle("Affect specific player?", setPlayer);
                    if (setPlayer)
                    {
                        ChoosePlayerGUI();
                    }
                }
                else
                {
                    setPlayer = false;
                }
            }
            else
            {
                EditorGUILayout.HelpBox("An Inventory Manager must be assigned for this Action to work", MessageType.Warning);
            }

            AfterRunningOption();
        }
示例#4
0
        private void InvInteractionGUI()
        {
            EditorGUILayout.BeginVertical("Button");
            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.LabelField("Inventory interactions", EditorStyles.boldLabel);

            if (GUILayout.Button(addContent, EditorStyles.miniButtonRight, buttonWidth))
            {
                Undo.RecordObject(_target, "Create inventory interaction");
                _target.invButtons.Add(new Button());
                _target.provideInvInteraction = true;
            }
            EditorGUILayout.EndHorizontal();

            if (_target.provideInvInteraction)
            {
                if (inventoryManager)
                {
                    // Create a string List of the field's names (for the PopUp box)
                    List <string> labelList = new List <string>();
                    int           invNumber;

                    if (inventoryManager.items.Count > 0)
                    {
                        foreach (InvItem _item in inventoryManager.items)
                        {
                            labelList.Add(_item.label);
                        }

                        foreach (Button invButton in _target.invButtons)
                        {
                            invNumber = -1;

                            int    j       = 0;
                            string invName = "";
                            foreach (InvItem _item in inventoryManager.items)
                            {
                                // If an item has been removed, make sure selected variable is still valid
                                if (_item.id == invButton.invID)
                                {
                                    invNumber = j;
                                    invName   = _item.label;
                                    break;
                                }

                                j++;
                            }

                            if (invNumber == -1)
                            {
                                // Wasn't found (item was deleted?), so revert to zero
                                ACDebug.Log("Previously chosen item no longer exists!");
                                invNumber       = 0;
                                invButton.invID = 0;
                            }

                            EditorGUILayout.Space();
                            EditorGUILayout.BeginHorizontal();

                            invNumber = EditorGUILayout.Popup("Inventory item:", invNumber, labelList.ToArray());

                            // Re-assign variableID based on PopUp selection
                            invButton.invID = inventoryManager.items[invNumber].id;

                            if (_target.GetComponent <Char>() && settingsManager != null && settingsManager.CanGiveItems())
                            {
                                invButton.selectItemMode = (SelectItemMode)EditorGUILayout.EnumPopup(invButton.selectItemMode, GUILayout.Width(70f));
                            }

                            if (GUILayout.Button(Resource.CogIcon, EditorStyles.miniButtonRight, buttonWidth))
                            {
                                SideMenu("Inv", _target.invButtons.Count, _target.invButtons.IndexOf(invButton));
                            }


                            EditorGUILayout.EndHorizontal();
                            if (invName != "")
                            {
                                string label = invName;
                                if (_target.GetComponent <Char>() && settingsManager != null && settingsManager.CanGiveItems())
                                {
                                    label = invButton.selectItemMode.ToString() + " " + label;
                                }
                                ButtonGUI(invButton, label, _target.interactionSource);
                            }
                            else
                            {
                                ButtonGUI(invButton, "Inventory", _target.interactionSource);
                            }
                            GUILayout.Box("", GUILayout.ExpandWidth(true), GUILayout.Height(1));
                        }
                    }
                    else
                    {
                        EditorGUILayout.LabelField("No inventory items exist!");
                        invNumber = -1;

                        for (int i = 0; i < _target.invButtons.Count; i++)
                        {
                            _target.invButtons[i].invID = -1;
                        }
                    }
                }
                else
                {
                    ACDebug.LogWarning("An InventoryManager is required to run the game properly - please open the Adventure Creator wizard and set one.");
                }
            }

            EditorGUILayout.EndVertical();
        }
示例#5
0
        private void ShowLocateButton(int languageIndex, bool forLipSync = false)
        {
            if (GUILayout.Button("Ping file"))
            {
                string language = (languageIndex == 0) ? string.Empty : AdvGame.GetReferences().speechManager.languages[languageIndex];
                string fullName = string.Empty;

                Object foundClp = null;

                if (KickStarter.settingsManager != null && SeparatePlayerAudio())
                {
                    foreach (PlayerPrefab player in KickStarter.settingsManager.players)
                    {
                        if (player != null && player.playerOb != null)
                        {
                            fullName = GetAutoAssetPathAndName(language, forLipSync, player.playerOb.name);

                            if (forLipSync)
                            {
                                if (KickStarter.speechManager.lipSyncMode == LipSyncMode.RogoLipSync)
                                {
                                    Object lipSyncFile = RogoLipSyncIntegration.GetObjectToPing(fullName);
                                    if (lipSyncFile != null)
                                    {
                                        foundClp = lipSyncFile;
                                    }
                                }
                                else
                                {
                                    TextAsset textFile = Resources.Load(fullName) as TextAsset;
                                    if (textFile != null)
                                    {
                                        foundClp = textFile;
                                    }
                                }
                            }
                            else
                            {
                                AudioClip clipObj = Resources.Load(fullName) as AudioClip;
                                if (clipObj != null)
                                {
                                    foundClp = clipObj;
                                    break;
                                }
                            }
                        }
                    }
                }
                else
                {
                    fullName = GetAutoAssetPathAndName(language, forLipSync);

                    if (forLipSync)
                    {
                        if (KickStarter.speechManager.lipSyncMode == LipSyncMode.RogoLipSync)
                        {
                            foundClp = RogoLipSyncIntegration.GetObjectToPing(fullName);
                        }
                        else
                        {
                            TextAsset textFile = Resources.Load(fullName) as TextAsset;
                            foundClp = textFile;
                        }
                    }
                    else
                    {
                        AudioClip clipObj = Resources.Load(fullName) as AudioClip;
                        foundClp = clipObj;
                    }
                }

                if (foundClp != null)
                {
                    EditorGUIUtility.PingObject(foundClp);
                }
                else
                {
                    ACDebug.Log(((forLipSync) ? "Text" : "Audio") + " file '/Resources/" + fullName + "' was found.");
                }
            }
        }
示例#6
0
        override public float Run()
        {
            if (_gameObject == null)
            {
                return(0f);
            }

            if (invAction == InvAction.Add)
            {
                // Instantiate

                GameObject oldOb = AssignFile(constantID, _gameObject);
                if (_gameObject.activeInHierarchy || (oldOb != null && oldOb.activeInHierarchy))
                {
                    ACDebug.Log(gameObject.name + " won't be instantiated, as it is already present in the scene.");
                    return(0f);
                }

                Vector3    position = _gameObject.transform.position;
                Quaternion rotation = _gameObject.transform.rotation;

                if (positionRelativeTo != PositionRelativeTo.Nothing)
                {
                    float forward = _gameObject.transform.position.z;
                    float right   = _gameObject.transform.position.x;
                    float up      = _gameObject.transform.position.y;

                    if (positionRelativeTo == PositionRelativeTo.RelativeToActiveCamera)
                    {
                        Transform mainCam = KickStarter.mainCamera.transform;
                        position              = mainCam.position + (mainCam.forward * forward) + (mainCam.right * right) + (mainCam.up * up);
                        rotation.eulerAngles += mainCam.transform.rotation.eulerAngles;
                    }
                    else if (positionRelativeTo == PositionRelativeTo.RelativeToPlayer)
                    {
                        if (KickStarter.player)
                        {
                            Transform playerTranform = KickStarter.player.transform;
                            position              = playerTranform.position + (playerTranform.forward * forward) + (playerTranform.right * right) + (playerTranform.up * up);
                            rotation.eulerAngles += playerTranform.rotation.eulerAngles;
                        }
                    }
                }

                GameObject newObject = (GameObject)Instantiate(_gameObject, position, rotation);
                newObject.name = _gameObject.name;
                KickStarter.stateHandler.GatherObjects();
            }
            else if (invAction == InvAction.Remove)
            {
                // Delete
                KickStarter.sceneSettings.ScheduleForDeletion(_gameObject);
            }
            else if (invAction == InvAction.Replace)
            {
                if (replaceGameObject == null)
                {
                    ACDebug.LogWarning("Cannot perform swap because the object to remove was not found in the scene.");
                    return(0f);
                }

                Vector3    position = replaceGameObject.transform.position;
                Quaternion rotation = replaceGameObject.transform.rotation;

                GameObject oldOb = AssignFile(constantID, _gameObject);
                if (gameObject.activeInHierarchy || (oldOb != null && oldOb.activeInHierarchy))
                {
                    ACDebug.Log(gameObject.name + " won't be instantiated, as it is already present in the scene.");
                    return(0f);
                }

                KickStarter.sceneSettings.ScheduleForDeletion(replaceGameObject);

                GameObject newObject = (GameObject)Instantiate(_gameObject, position, rotation);
                newObject.name = _gameObject.name;
                KickStarter.stateHandler.GatherObjects();
            }

            return(0f);
        }
示例#7
0
        override public float Run()
        {
            if (KickStarter.settingsManager.playerSwitching == PlayerSwitching.Allow)
            {
                if (KickStarter.sceneChanger.GetSubScenes().Length > 0)
                {
                    //	ACDebug.LogWarning ("Cannot switch players while multiple scenes are open!");
                    //	return 0f;
                }

                if (KickStarter.settingsManager.players.Count > 0 && KickStarter.settingsManager.players.Count > playerNumber && playerNumber > -1)
                {
                    if (KickStarter.player != null && KickStarter.player.ID == playerID)
                    {
                        ACDebug.Log("Cannot switch player - already controlling the desired prefab.");
                        return(0f);
                    }

                    if (KickStarter.settingsManager.players[playerNumber].playerOb != null)
                    {
                        KickStarter.saveSystem.SaveCurrentPlayerData();

                        Vector3    oldPlayerPosition = Vector3.zero;
                        Quaternion oldPlayerRotation = new Quaternion();
                        Vector3    oldPlayerScale    = Vector3.one;

                        if (KickStarter.player != null)
                        {
                            oldPlayerPosition = KickStarter.player.transform.position;
                            oldPlayerRotation = KickStarter.player.TransformRotation;
                            oldPlayerScale    = KickStarter.player.transform.localScale;
                        }

                        if (newPlayerPosition != NewPlayerPosition.ReplaceCurrentPlayer)
                        {
                            if (oldPlayer == OldPlayer.ReplaceWithAssociatedNPC && (oldPlayerNPC == null || !oldPlayerNPC.gameObject.activeInHierarchy) && KickStarter.player.associatedNPCPrefab != null)
                            {
                                GameObject newObject = (GameObject)Instantiate(KickStarter.player.associatedNPCPrefab.gameObject);
                                newObject.name = KickStarter.player.associatedNPCPrefab.gameObject.name;
                                oldPlayerNPC   = newObject.GetComponent <NPC>();
                            }

                            if ((oldPlayer == OldPlayer.ReplaceWithNPC || oldPlayer == OldPlayer.ReplaceWithAssociatedNPC) &&
                                oldPlayerNPC != null && oldPlayerNPC.gameObject.activeInHierarchy)
                            {
                                oldPlayerNPC.transform.position   = oldPlayerPosition;
                                oldPlayerNPC.TransformRotation    = oldPlayerRotation;
                                oldPlayerNPC.transform.localScale = oldPlayerScale;

                                // Force the rotation / sprite child to update
                                oldPlayerNPC._Update();
                            }
                        }

                        if (newPlayerNPC == null || newPlayerPosition == NewPlayerPosition.ReplaceAssociatedNPC)
                        {
                            // Try to find from associated NPC prefab

                            if (KickStarter.settingsManager.players[playerNumber].playerOb.associatedNPCPrefab != null)
                            {
                                ConstantID prefabID = KickStarter.settingsManager.players[playerNumber].playerOb.associatedNPCPrefab.GetComponent <ConstantID>();
                                if (prefabID != null && prefabID.constantID != 0)
                                {
                                    newPlayerNPC_ID = prefabID.constantID;
                                    newPlayerNPC    = AssignFile <NPC> (prefabID.constantID, null);
                                }
                            }
                        }

                        Quaternion newRotation = Quaternion.identity;
                        if (newPlayerPosition == NewPlayerPosition.ReplaceCurrentPlayer)
                        {
                            newRotation = oldPlayerRotation;
                        }
                        else if (newPlayerPosition == NewPlayerPosition.ReplaceNPC && newPlayerNPC)
                        {
                            newRotation = newPlayerNPC.TransformRotation;
                        }
                        else if (newPlayerPosition == NewPlayerPosition.AppearAtMarker && newPlayerMarker)
                        {
                            newRotation = newPlayerMarker.transform.rotation;
                        }

                        KickStarter.ResetPlayer(KickStarter.settingsManager.players[playerNumber].playerOb, playerID, true, newRotation, keepInventory);
                        Player newPlayer = KickStarter.player;
                        PlayerMenus.ResetInventoryBoxes();

                        if (restorePreviousData && KickStarter.saveSystem.DoesPlayerDataExist(playerID, true))
                        {
                            if (newPlayerNPC)
                            {
                                newPlayerNPC.transform.position += new Vector3(100f, -100f, 100f);
                            }

                            int sceneToLoad = KickStarter.saveSystem.GetPlayerScene(playerID);
                            if (sceneToLoad >= 0 && sceneToLoad != UnityVersionHandler.GetCurrentSceneNumber())
                            {
                                KickStarter.saveSystem.loadingGame = LoadingGame.JustSwitchingPlayer;
                                KickStarter.sceneChanger.ChangeScene(new SceneInfo("", sceneToLoad), true, false, newPlayerNPC_ID);
                            }
                            else
                            {
                                string sceneToLoadName = KickStarter.saveSystem.GetPlayerSceneName(playerID);
                                if (sceneToLoadName != "" && sceneToLoadName != UnityVersionHandler.GetCurrentSceneName())
                                {
                                    KickStarter.saveSystem.loadingGame = LoadingGame.JustSwitchingPlayer;
                                    KickStarter.sceneChanger.ChangeScene(new SceneInfo(sceneToLoadName, -1), true, false, newPlayerNPC_ID);
                                }
                            }
                        }
                        else
                        {
                            // No data to restore

                            if (newPlayerPosition == NewPlayerPosition.ReplaceCurrentPlayer)
                            {
                                newPlayer.Teleport(oldPlayerPosition);
                                newPlayer.SetRotation(oldPlayerRotation);
                                newPlayer.transform.localScale = oldPlayerScale;
                            }
                            else if (newPlayerPosition == NewPlayerPosition.ReplaceNPC || newPlayerPosition == NewPlayerPosition.ReplaceAssociatedNPC)
                            {
                                if (newPlayerNPC)
                                {
                                    newPlayer.Teleport(newPlayerNPC.transform.position);
                                    newPlayer.SetRotation(newPlayerNPC.TransformRotation);
                                    newPlayer.transform.localScale = newPlayerNPC.transform.localScale;

                                    newPlayerNPC.transform.position += new Vector3(100f, -100f, 100f);
                                }
                            }
                            else if (newPlayerPosition == NewPlayerPosition.AppearAtMarker)
                            {
                                if (newPlayerMarker)
                                {
                                    newPlayer.Teleport(newPlayerMarker.transform.position);
                                    newPlayer.SetRotation(newPlayerMarker.transform.rotation);
                                    newPlayer.transform.localScale = newPlayerMarker.transform.localScale;
                                }
                            }
                            else if (newPlayerPosition == NewPlayerPosition.AppearInOtherScene)
                            {
                                if (chooseNewSceneBy == ChooseSceneBy.Name && newPlayerSceneName == UnityVersionHandler.GetCurrentSceneName() ||
                                    (chooseNewSceneBy == ChooseSceneBy.Number && newPlayerScene == UnityVersionHandler.GetCurrentSceneNumber()))
                                {
                                    // Already in correct scene
                                    if (newPlayerNPC && newPlayerNPC.gameObject.activeInHierarchy)
                                    {
                                        newPlayer.Teleport(newPlayerNPC.transform.position);
                                        newPlayer.SetRotation(newPlayerNPC.TransformRotation);
                                        newPlayer.transform.localScale = newPlayerNPC.transform.localScale;

                                        newPlayerNPC.transform.position += new Vector3(100f, -100f, 100f);
                                    }
                                }
                                else
                                {
                                    if (newPlayerNPC && newPlayerNPC.gameObject.activeInHierarchy)
                                    {
                                        newPlayerNPC.transform.position += new Vector3(100f, -100f, 100f);
                                    }

                                    //KickStarter.saveSystem.loadingGame = LoadingGame.JustSwitchingPlayer;
                                    KickStarter.sceneChanger.ChangeScene(new SceneInfo(chooseNewSceneBy, newPlayerSceneName, newPlayerScene), true, false, newPlayerNPC_ID, true);
                                }
                            }
                        }

                        if (KickStarter.mainCamera.attachedCamera)
                        {
                            KickStarter.mainCamera.attachedCamera.MoveCameraInstant();
                        }

                        AssetLoader.UnloadAssets();
                    }
                    else
                    {
                        ACDebug.LogWarning("Cannot switch player - no player prefabs is defined.");
                    }
                }
            }

            return(0f);
        }
示例#8
0
        private void ConvertGlobalToLocal(GVar globalVariable)
        {
            if (globalVariable == null)
            {
                return;
            }

            if (KickStarter.localVariables == null)
            {
                ACDebug.LogWarning("Cannot convert variable to local since the scene has not been prepared for AC.");
                return;
            }

            if (EditorUtility.DisplayDialog("Convert " + globalVariable.label + " to Local Variable?", "This will update all Actions and Managers that refer to this Variable.  This is a non-reversible process, and you should back up your project first. Continue?", "OK", "Cancel"))
            {
                if (UnityVersionHandler.SaveSceneIfUserWants())
                {
                    // Create new Local
                    DeactivateAllVars();
                    GVar newLocalVariable = new GVar(globalVariable);
                    int  newLocalID       = newLocalVariable.AssignUniqueID(GetIDArray(KickStarter.localVariables.localVars));
                    KickStarter.localVariables.localVars.Add(newLocalVariable);
                    UnityVersionHandler.CustomSetDirty(KickStarter.localVariables, true);
                    UnityVersionHandler.SaveScene();

                    // Update current scene
                    bool   updatedScene  = false;
                    string originalScene = UnityVersionHandler.GetCurrentSceneFilepath();

                    ActionList[] actionLists = FindObjectsOfType <ActionList>();
                    foreach (ActionList actionList in actionLists)
                    {
                        foreach (Action action in actionList.actions)
                        {
                            bool updatedActionList = action.ConvertGlobalVariableToLocal(globalVariable.id, newLocalID, true);
                            if (updatedActionList)
                            {
                                updatedScene = true;
                                UnityVersionHandler.CustomSetDirty(actionList, true);
                                ACDebug.Log("Updated Action " + actionList.actions.IndexOf(action) + " of ActionList '" + actionList.name + "' in scene '" + originalScene + "'", actionList);
                            }
                        }
                    }

                    Conversation[] conversations = FindObjectsOfType <Conversation>();
                    foreach (Conversation conversation in conversations)
                    {
                        bool updatedConversation = conversation.ConvertGlobalVariableToLocal(globalVariable.id, newLocalID, true);
                        if (updatedConversation)
                        {
                            updatedScene = true;
                            UnityVersionHandler.CustomSetDirty(conversation, true);
                            ACDebug.Log("Updated Conversation " + conversation + ") in scene '" + originalScene + "'");
                        }
                    }

                    if (updatedScene)
                    {
                        UnityVersionHandler.SaveScene();
                    }

                    // Update other scenes
                    string[] sceneFiles = AdvGame.GetSceneFiles();
                    foreach (string sceneFile in sceneFiles)
                    {
                        if (sceneFile == originalScene)
                        {
                            continue;
                        }
                        UnityVersionHandler.OpenScene(sceneFile);

                        actionLists = FindObjectsOfType <ActionList>();
                        foreach (ActionList actionList in actionLists)
                        {
                            foreach (Action action in actionList.actions)
                            {
                                bool isAffected = action.ConvertGlobalVariableToLocal(globalVariable.id, newLocalID, false);
                                if (isAffected)
                                {
                                    ACDebug.LogWarning("Cannot update Action " + actionList.actions.IndexOf(action) + " in ActionList '" + actionList.name + "' in scene '" + sceneFile + "' because it cannot access the Local Variable in scene '" + originalScene + "'.");
                                }
                            }
                        }

                        conversations = FindObjectsOfType <Conversation>();
                        foreach (Conversation conversation in conversations)
                        {
                            bool isAffected = conversation.ConvertGlobalVariableToLocal(globalVariable.id, newLocalID, false);
                            if (isAffected)
                            {
                                ACDebug.LogWarning("Cannot update Conversation " + conversation + ") in scene '" + sceneFile + "' because it cannot access the Local Variable in scene '" + originalScene + "'.");
                            }
                        }
                    }

                    UnityVersionHandler.OpenScene(originalScene);

                    // Update Menu Manager
                    if (KickStarter.menuManager)
                    {
                        KickStarter.menuManager.CheckConvertGlobalVariableToLocal(globalVariable.id, newLocalID);
                    }

                    //  Update Speech Manager
                    if (KickStarter.speechManager)
                    {
                        // Search asset files
                        ActionListAsset[] allActionListAssets = KickStarter.speechManager.GetAllActionListAssets();
                        UnityVersionHandler.OpenScene(originalScene);

                        if (allActionListAssets != null)
                        {
                            foreach (ActionListAsset actionListAsset in allActionListAssets)
                            {
                                foreach (Action action in actionListAsset.actions)
                                {
                                    bool isAffected = action.ConvertGlobalVariableToLocal(globalVariable.id, newLocalID, false);
                                    if (isAffected)
                                    {
                                        ACDebug.LogWarning("Cannot update Action " + actionListAsset.actions.IndexOf(action) + " in ActionList asset '" + actionListAsset.name + "' because asset files cannot refer to Local Variables.");
                                    }
                                }
                            }
                        }

                        KickStarter.speechManager.ConvertGlobalVariableToLocal(globalVariable, UnityVersionHandler.GetCurrentSceneName());
                    }

                    // Remove old Global
                    vars.Remove(globalVariable);

                    // Mark for saving
                    EditorUtility.SetDirty(this);
                    if (KickStarter.localVariables != null)
                    {
                        UnityVersionHandler.CustomSetDirty(KickStarter.localVariables);
                    }

                    AssetDatabase.SaveAssets();
                }
            }
        }
示例#9
0
        private List <VarPreset> ShowPresets(List <VarPreset> _varPresets, List <GVar> _vars, VariableLocation location)
        {
            if (_vars == null || _vars.Count == 0)
            {
                return(_varPresets);
            }

            if (!Application.isPlaying || _varPresets.Count > 0)
            {
                EditorGUILayout.BeginVertical(CustomStyles.thinBox);
                showPresets = CustomGUILayout.ToggleHeader(showPresets, "Preset configurations");
            }

            if (showPresets && (!Application.isPlaying || _varPresets.Count > 0))
            {
                List <string> labelList = new List <string>();

                int i            = 0;
                int presetNumber = -1;

                if (_varPresets.Count > 0)
                {
                    foreach (VarPreset _varPreset in _varPresets)
                    {
                        if (_varPreset.label != "")
                        {
                            labelList.Add(i.ToString() + ": " + _varPreset.label);
                        }
                        else
                        {
                            labelList.Add(i.ToString() + ": (Untitled)");
                        }

                        if (_varPreset.ID == chosenPresetID)
                        {
                            presetNumber = i;
                        }
                        i++;
                    }

                    if (presetNumber == -1)
                    {
                        chosenPresetID = 0;
                    }
                    else if (presetNumber >= _varPresets.Count)
                    {
                        presetNumber = Mathf.Max(0, _varPresets.Count - 1);
                    }
                    else
                    {
                        presetNumber   = EditorGUILayout.Popup("Created presets:", presetNumber, labelList.ToArray());
                        chosenPresetID = _varPresets[presetNumber].ID;
                    }
                }
                else
                {
                    chosenPresetID = presetNumber = -1;
                }

                if (presetNumber >= 0)
                {
                    string apiPrefix = ((location == VariableLocation.Local) ? "AC.KickStarter.localVariables.GetPreset (" + chosenPresetID + ")" : "AC.KickStarter.runtimeVariables.GetPreset (" + chosenPresetID + ")");

                    if (!Application.isPlaying)
                    {
                        _varPresets [presetNumber].label = CustomGUILayout.TextField("Preset name:", _varPresets [presetNumber].label, apiPrefix + ".label");
                    }

                    EditorGUILayout.BeginHorizontal();
                    if (!Application.isPlaying)
                    {
                        GUI.enabled = false;
                    }
                    if (GUILayout.Button("Bulk-assign"))
                    {
                        if (presetNumber >= 0 && _varPresets.Count > presetNumber)
                        {
                            if (location == VariableLocation.Global)
                            {
                                if (KickStarter.runtimeVariables)
                                {
                                    KickStarter.runtimeVariables.AssignFromPreset(_varPresets [presetNumber]);
                                    ACDebug.Log("Global variables updated to " + _varPresets [presetNumber].label);
                                }
                            }
                            else if (location == VariableLocation.Local)
                            {
                                if (KickStarter.localVariables)
                                {
                                    KickStarter.localVariables.AssignFromPreset(_varPresets [presetNumber]);
                                    ACDebug.Log("Local variables updated to " + _varPresets [presetNumber].label);
                                }
                            }
                        }
                    }

                    GUI.enabled = !Application.isPlaying;
                    if (GUILayout.Button("Delete"))
                    {
                        _varPresets.RemoveAt(presetNumber);
                        presetNumber   = 0;
                        chosenPresetID = 0;
                    }

                    GUI.enabled = true;
                    EditorGUILayout.EndHorizontal();
                }

                if (!Application.isPlaying)
                {
                    if (GUILayout.Button("Create new preset"))
                    {
                        VarPreset newVarPreset = new VarPreset(_vars, GetIDArray(_varPresets));
                        _varPresets.Add(newVarPreset);
                        chosenPresetID = newVarPreset.ID;
                    }
                }
            }
            if (!Application.isPlaying || _varPresets.Count > 0)
            {
                EditorGUILayout.EndVertical();
            }

            EditorGUILayout.Space();

            return(_varPresets);
        }
示例#10
0
        override public float Run()
        {
            if (KickStarter.settingsManager.playerSwitching == PlayerSwitching.Allow)
            {
                PlayerPrefab newPlayerPrefab = KickStarter.settingsManager.GetPlayerPrefab(playerID);

                if (newPlayerPrefab != null)
                {
                    if (KickStarter.player != null && KickStarter.player.ID == playerID)
                    {
                        ACDebug.Log("Cannot switch player - already controlling the desired prefab.");
                        return(0f);
                    }

                    if (newPlayerPrefab.playerOb != null)
                    {
                        KickStarter.saveSystem.SaveCurrentPlayerData();

                        Vector3    oldPlayerPosition = Vector3.zero;
                        Quaternion oldPlayerRotation = new Quaternion();
                        Vector3    oldPlayerScale    = Vector3.one;

                        PlayerData oldPlayerData         = new PlayerData();
                        NPCData    oldNPCData            = new NPCData();
                        bool       recordedOldPlayerData = false;
                        bool       recordedOldNPCData    = false;

                        if (KickStarter.player != null)
                        {
                            oldPlayerPosition = KickStarter.player.transform.position;
                            oldPlayerRotation = KickStarter.player.TransformRotation;
                            oldPlayerScale    = KickStarter.player.transform.localScale;

                            oldPlayerData         = KickStarter.player.SavePlayerData(oldPlayerData);
                            recordedOldPlayerData = true;
                        }

                        if (newPlayerPosition != NewPlayerPosition.ReplaceCurrentPlayer)
                        {
                            if (oldPlayer == OldPlayer.ReplaceWithAssociatedNPC &&
                                (runtimeOldPlayerNPC == null || !runtimeOldPlayerNPC.gameObject.activeInHierarchy) &&
                                KickStarter.player.associatedNPCPrefab != null)
                            {
                                GameObject newObject = (GameObject)Instantiate(KickStarter.player.associatedNPCPrefab.gameObject);
                                newObject.name      = KickStarter.player.associatedNPCPrefab.gameObject.name;
                                runtimeOldPlayerNPC = newObject.GetComponent <NPC>();
                            }

                            if ((oldPlayer == OldPlayer.ReplaceWithNPC || oldPlayer == OldPlayer.ReplaceWithAssociatedNPC) &&
                                runtimeOldPlayerNPC != null && runtimeOldPlayerNPC.gameObject.activeInHierarchy)
                            {
                                runtimeOldPlayerNPC.transform.position   = oldPlayerPosition;
                                runtimeOldPlayerNPC.TransformRotation    = oldPlayerRotation;
                                runtimeOldPlayerNPC.transform.localScale = oldPlayerScale;

                                if (recordedOldPlayerData)
                                {
                                    ApplyRenderData(runtimeOldPlayerNPC, oldPlayerData);
                                }

                                // Force the rotation / sprite child to update
                                runtimeOldPlayerNPC._Update();
                            }
                        }

                        if (runtimeNewPlayerNPC == null || newPlayerPosition == NewPlayerPosition.ReplaceAssociatedNPC)
                        {
                            // Try to find from associated NPC prefab

                            if (newPlayerPrefab.playerOb.associatedNPCPrefab != null)
                            {
                                ConstantID prefabID = newPlayerPrefab.playerOb.associatedNPCPrefab.GetComponent <ConstantID>();
                                if (prefabID != null && prefabID.constantID != 0)
                                {
                                    newPlayerNPC_ID     = prefabID.constantID;
                                    runtimeNewPlayerNPC = AssignFile <NPC> (prefabID.constantID, null);
                                }
                            }
                        }

                        Quaternion newRotation = Quaternion.identity;
                        if (newPlayerPosition == NewPlayerPosition.ReplaceCurrentPlayer)
                        {
                            newRotation = oldPlayerRotation;
                        }
                        else if (newPlayerPosition == NewPlayerPosition.ReplaceNPC && runtimeNewPlayerNPC != null)
                        {
                            newRotation = runtimeNewPlayerNPC.TransformRotation;
                        }
                        else if (newPlayerPosition == NewPlayerPosition.AppearAtMarker && runtimeNewPlayerMarker != null)
                        {
                            newRotation = runtimeNewPlayerMarker.transform.rotation;
                        }

                        if (runtimeNewPlayerNPC != null)
                        {
                            oldNPCData = runtimeNewPlayerNPC.SaveData(oldNPCData);
                        }

                        bool replacesOldPlayer = newPlayerPosition == NewPlayerPosition.ReplaceCurrentPlayer &&
                                                 (!restorePreviousData || !KickStarter.saveSystem.DoesPlayerDataExist(playerID, true));
                        KickStarter.ResetPlayer(newPlayerPrefab.playerOb, playerID, true, newRotation, keepInventory, false, replacesOldPlayer, alwaysSnapCamera);
                        Player newPlayer = KickStarter.player;
                        PlayerMenus.ResetInventoryBoxes();

                        if (replacesOldPlayer && recordedOldPlayerData)
                        {
                            ApplyRenderData(newPlayer, oldPlayerData);
                        }

                        if (restorePreviousData && KickStarter.saveSystem.DoesPlayerDataExist(playerID, true))
                        {
                            int    sceneToLoad     = KickStarter.saveSystem.GetPlayerScene(playerID);
                            string sceneToLoadName = KickStarter.saveSystem.GetPlayerSceneName(playerID);

                            if (sceneToLoad >= 0 && sceneToLoad != UnityVersionHandler.GetCurrentSceneNumber())
                            {
                                KickStarter.saveSystem.loadingGame = LoadingGame.JustSwitchingPlayer;
                                KickStarter.sceneChanger.ChangeScene(new SceneInfo(string.Empty, sceneToLoad), true, false);
                            }
                            else if (!string.IsNullOrEmpty(sceneToLoadName) && sceneToLoadName != UnityVersionHandler.GetCurrentSceneName())
                            {
                                KickStarter.saveSystem.loadingGame = LoadingGame.JustSwitchingPlayer;
                                KickStarter.sceneChanger.ChangeScene(new SceneInfo(sceneToLoadName, -1), true, false);
                            }
                            else
                            {
                                // Same scene
                                if (runtimeNewPlayerNPC != null)
                                {
                                    newPlayer.RepositionToTransform(runtimeNewPlayerNPC.transform);
                                    runtimeNewPlayerNPC.HideFromView(newPlayer);
                                }
                            }
                        }
                        else
                        {
                            // No data to restore

                            if (newPlayerPosition == NewPlayerPosition.ReplaceCurrentPlayer)
                            {
                                newPlayer.Teleport(oldPlayerPosition);
                                newPlayer.SetRotation(oldPlayerRotation);
                                newPlayer.transform.localScale = oldPlayerScale;
                            }
                            else if (newPlayerPosition == NewPlayerPosition.ReplaceNPC || newPlayerPosition == NewPlayerPosition.ReplaceAssociatedNPC)
                            {
                                if (runtimeNewPlayerNPC != null)
                                {
                                    newPlayer.RepositionToTransform(runtimeNewPlayerNPC.transform);
                                    runtimeNewPlayerNPC.HideFromView(newPlayer);

                                    if (recordedOldNPCData)
                                    {
                                        ApplyRenderData(newPlayer, oldNPCData);
                                    }
                                }
                            }
                            else if (newPlayerPosition == NewPlayerPosition.AppearAtMarker)
                            {
                                if (runtimeNewPlayerMarker)
                                {
                                    newPlayer.RepositionToTransform(runtimeNewPlayerMarker.transform);
                                }
                            }
                            else if (newPlayerPosition == NewPlayerPosition.AppearInOtherScene)
                            {
                                if (chooseNewSceneBy == ChooseSceneBy.Name && newPlayerSceneName == UnityVersionHandler.GetCurrentSceneName() ||
                                    (chooseNewSceneBy == ChooseSceneBy.Number && newPlayerScene == UnityVersionHandler.GetCurrentSceneNumber()))
                                {
                                    // Already in correct scene
                                    if (runtimeNewPlayerNPC && runtimeNewPlayerNPC.gameObject.activeInHierarchy)
                                    {
                                        newPlayer.RepositionToTransform(runtimeNewPlayerNPC.transform);
                                        runtimeNewPlayerNPC.HideFromView(newPlayer);
                                    }
                                }
                                else
                                {
                                    KickStarter.sceneChanger.ChangeScene(new SceneInfo(chooseNewSceneBy, newPlayerSceneName, newPlayerScene), true, false, true);
                                }
                            }
                        }

                        if (KickStarter.mainCamera.attachedCamera && alwaysSnapCamera)
                        {
                            KickStarter.mainCamera.attachedCamera.MoveCameraInstant();
                        }

                        AssetLoader.UnloadAssets();
                    }
                    else
                    {
                        ACDebug.LogWarning("Cannot switch player - no player prefabs is defined.");
                    }
                }
            }

            return(0f);
        }
示例#11
0
        private void ConvertLocalToGlobal(GVar localVariable, int localIndex)
        {
            if (localVariable == null)
            {
                return;
            }

            if (EditorUtility.DisplayDialog("Convert " + localVariable.label + " to Global Variable?", "This will update all Actions and Managers that refer to this Variable.  This is a non-reversible process, and you should back up your project first. Continue?", "OK", "Cancel"))
            {
                if (UnityVersionHandler.SaveSceneIfUserWants())
                {
                    // Create new Global
                    DeactivateAllVars();
                    GVar newGlobalVariable = new GVar(localVariable);
                    int  newGlobalID       = newGlobalVariable.AssignUniqueID(GetIDArray(vars));
                    vars.Add(newGlobalVariable);

                    // Update current scene
                    bool         updatedScene = false;
                    ActionList[] actionLists  = FindObjectsOfType <ActionList>();
                    foreach (ActionList actionList in actionLists)
                    {
                        foreach (Action action in actionList.actions)
                        {
                            bool updatedActionList = action.ConvertLocalVariableToGlobal(localVariable.id, newGlobalID);
                            if (updatedActionList)
                            {
                                updatedScene = true;
                                UnityVersionHandler.CustomSetDirty(actionList, true);
                                ACDebug.Log("Updated Action " + actionList.actions.IndexOf(action) + " of ActionList '" + actionList.name + "'", actionList);
                            }
                        }
                    }

                    Conversation[] conversations = FindObjectsOfType <Conversation>();
                    foreach (Conversation conversation in conversations)
                    {
                        bool updatedConversation = conversation.ConvertLocalVariableToGlobal(localVariable.id, newGlobalID);
                        if (updatedConversation)
                        {
                            updatedScene = true;
                            UnityVersionHandler.CustomSetDirty(conversation, true);
                            ACDebug.Log("Updated Conversation '" + conversation + "'");
                        }
                    }

                    if (updatedScene)
                    {
                        UnityVersionHandler.SaveScene();
                    }

                    // Update Speech Manager
                    if (KickStarter.speechManager)
                    {
                        KickStarter.speechManager.ConvertLocalVariableToGlobal(localVariable, newGlobalID);
                    }

                    // Remove old Local
                    KickStarter.localVariables.localVars.RemoveAt(localIndex);
                    EditorUtility.SetDirty(KickStarter.localVariables);
                    UnityVersionHandler.SaveScene();

                    // Mark for saving
                    EditorUtility.SetDirty(this);

                    AssetDatabase.SaveAssets();
                }
            }
        }
        private void Export()
        {
                        #if UNITY_WEBPLAYER
            ACDebug.LogWarning("Game text cannot be exported in WebPlayer mode - please switch platform and try again.");
                        #else
            if (inventoryManager == null || exportColumns == null || exportColumns.Count == 0 || inventoryManager.items == null || inventoryManager.items.Count == 0)
            {
                return;
            }

            string suggestedFilename = "";
            if (AdvGame.GetReferences().settingsManager)
            {
                suggestedFilename = AdvGame.GetReferences().settingsManager.saveFileName + " - ";
            }
            suggestedFilename += "Inventory.csv";

            string fileName = EditorUtility.SaveFilePanel("Export inventory items", "Assets", suggestedFilename, "csv");
            if (fileName.Length == 0)
            {
                return;
            }

            List <InvItem> exportItems = new List <InvItem>();
            foreach (InvItem item in inventoryManager.items)
            {
                exportItems.Add(new InvItem(item));
            }

            bool            fail   = false;
            List <string[]> output = new List <string[]>();

            List <string> headerList = new List <string>();
            headerList.Add("ID");
            foreach (ExportColumn exportColumn in exportColumns)
            {
                headerList.Add(exportColumn.GetHeader());
            }
            output.Add(headerList.ToArray());

            foreach (InvItem exportItem in exportItems)
            {
                List <string> rowList = new List <string>();
                rowList.Add(exportItem.id.ToString());
                foreach (ExportColumn exportColumn in exportColumns)
                {
                    string cellText = exportColumn.GetCellText(exportItem, inventoryManager);
                    rowList.Add(cellText);

                    if (cellText.Contains(CSVReader.csvDelimiter))
                    {
                        fail = true;
                        ACDebug.LogError("Cannot export inventory since item " + exportItem.id.ToString() + " (" + exportItem.label + ") contains the character '" + CSVReader.csvDelimiter + "'.");
                    }
                }
                output.Add(rowList.ToArray());
            }

            if (!fail)
            {
                int length = output.Count;

                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                for (int j = 0; j < length; j++)
                {
                    sb.AppendLine(string.Join(CSVReader.csvDelimiter, output[j]));
                }

                if (Serializer.SaveFile(fileName, sb.ToString()))
                {
                    ACDebug.Log((exportItems.Count - 1).ToString() + " items exported.");
                }
            }

            //this.Close ();
                        #endif
        }
示例#13
0
        public void OnAwake()
        {
            ClearVariables();

            // Test for key imports
            References references = (References)Resources.Load(Resource.references);

            if (references)
            {
                SceneManager     sceneManager     = AdvGame.GetReferences().sceneManager;
                SettingsManager  settingsManager  = AdvGame.GetReferences().settingsManager;
                ActionsManager   actionsManager   = AdvGame.GetReferences().actionsManager;
                InventoryManager inventoryManager = AdvGame.GetReferences().inventoryManager;
                VariablesManager variablesManager = AdvGame.GetReferences().variablesManager;
                SpeechManager    speechManager    = AdvGame.GetReferences().speechManager;
                CursorManager    cursorManager    = AdvGame.GetReferences().cursorManager;
                MenuManager      menuManager      = AdvGame.GetReferences().menuManager;

                if (sceneManager == null)
                {
                    ACDebug.LogError("No Scene Manager found - please set one using the Adventure Creator Kit wizard");
                }

                if (settingsManager == null)
                {
                    ACDebug.LogError("No Settings Manager found - please set one using the Adventure Creator Kit wizard");
                }
                else
                {
                    if (settingsManager.IsInLoadingScene())
                    {
                        ACDebug.Log("Bypassing regular AC startup because the current scene is the 'Loading' scene.");
                        SetPersistentEngine();
                        return;
                    }

                    // Unity 5.3 has a bug whereby a modified Player prefab is placed in the scene when editing, but not visible
                    // This causes the Player to not load properly, so try to detect this remnant and delete it!
                    GameObject existingPlayer = GameObject.FindGameObjectWithTag(Tags.player);
                    if (existingPlayer != null)
                    {
                        if (settingsManager.GetDefaultPlayer() != null && existingPlayer.name == (settingsManager.GetDefaultPlayer().name + "(Clone)"))
                        {
                            DestroyImmediate(GameObject.FindGameObjectWithTag(Tags.player));
                            ACDebug.LogWarning("Player clone found in scene - this may have been hidden by a Unity bug, and has been destroyed.");
                        }
                    }

                    if (!GameObject.FindGameObjectWithTag(Tags.player))
                    {
                        KickStarter.ResetPlayer(settingsManager.GetDefaultPlayer(), settingsManager.GetDefaultPlayerID(), false, Quaternion.identity);
                    }
                    else
                    {
                        KickStarter.playerPrefab = GameObject.FindWithTag(Tags.player).GetComponent <Player>();

                        if (sceneChanger == null || sceneChanger.GetPlayerOnTransition() == null)
                        {
                            // New local player
                            if (KickStarter.playerPrefab != null)
                            {
                                KickStarter.playerPrefab.Initialise();
                            }
                        }

                        AssignLocalPlayer();
                    }
                }

                if (actionsManager == null)
                {
                    ACDebug.LogError("No Actions Manager found - please set one using the main Adventure Creator window");
                }

                if (inventoryManager == null)
                {
                    ACDebug.LogError("No Inventory Manager found - please set one using the main Adventure Creator window");
                }

                if (variablesManager == null)
                {
                    ACDebug.LogError("No Variables Manager found - please set one using the main Adventure Creator window");
                }

                if (speechManager == null)
                {
                    ACDebug.LogError("No Speech Manager found - please set one using the main Adventure Creator window");
                }

                if (cursorManager == null)
                {
                    ACDebug.LogError("No Cursor Manager found - please set one using the main Adventure Creator window");
                }

                if (menuManager == null)
                {
                    ACDebug.LogError("No Menu Manager found - please set one using the main Adventure Creator window");
                }

                if (GameObject.FindWithTag(Tags.player) == null && KickStarter.settingsManager.movementMethod != MovementMethod.None)
                {
                    ACDebug.LogWarning("No Player found - please set one using the Settings Manager, tagging it as Player and placing it in a Resources folder");
                }
            }
            else
            {
                ACDebug.LogError("No References object found. Please set one using the main Adventure Creator window");
            }

            SetPersistentEngine();

            if (persistentEnginePrefab == null)
            {
                ACDebug.LogError("No PersistentEngine prefab found - please place one in the Resources directory, and tag it as PersistentEngine");
            }
            else
            {
                if (persistentEnginePrefab.GetComponent <Options>() == null)
                {
                    ACDebug.LogError(persistentEnginePrefab.name + " has no Options component attached.");
                }
                if (persistentEnginePrefab.GetComponent <RuntimeInventory>() == null)
                {
                    ACDebug.LogError(persistentEnginePrefab.name + " has no RuntimeInventory component attached.");
                }
                if (persistentEnginePrefab.GetComponent <RuntimeVariables>() == null)
                {
                    ACDebug.LogError(persistentEnginePrefab.name + " has no RuntimeVariables component attached.");
                }
                if (persistentEnginePrefab.GetComponent <PlayerMenus>() == null)
                {
                    ACDebug.LogError(persistentEnginePrefab.name + " has no PlayerMenus component attached.");
                }
                if (persistentEnginePrefab.GetComponent <StateHandler>() == null)
                {
                    ACDebug.LogError(persistentEnginePrefab.name + " has no StateHandler component attached.");
                }
                if (persistentEnginePrefab.GetComponent <SceneChanger>() == null)
                {
                    ACDebug.LogError(persistentEnginePrefab.name + " has no SceneChanger component attached.");
                }
                if (persistentEnginePrefab.GetComponent <SaveSystem>() == null)
                {
                    ACDebug.LogError(persistentEnginePrefab.name + " has no SaveSystem component attached.");
                }
                if (persistentEnginePrefab.GetComponent <LevelStorage>() == null)
                {
                    ACDebug.LogError(persistentEnginePrefab.name + " has no LevelStorage component attached.");
                }
                if (persistentEnginePrefab.GetComponent <RuntimeLanguages>() == null)
                {
                    ACDebug.LogError(persistentEnginePrefab.name + " has no RuntimeLanguages component attached.");
                }
                if (persistentEnginePrefab.GetComponent <ActionListAssetManager>() == null)
                {
                    ACDebug.LogError(persistentEnginePrefab.name + " has no ActionListAssetManager component attached.");
                }
            }

            if (GameObject.FindWithTag(Tags.mainCamera) == null)
            {
                ACDebug.LogWarning("No MainCamera found - please click 'Organise room objects' in the Scene Manager to create one.");
            }
            else
            {
                if (GameObject.FindWithTag(Tags.mainCamera).GetComponent <MainCamera>() == null &&
                    GameObject.FindWithTag(Tags.mainCamera).GetComponentInParent <MainCamera>() == null)
                {
                    ACDebug.LogError("MainCamera has no MainCamera component.");
                }
            }

            if (this.GetComponent <MenuSystem>() == null)
            {
                ACDebug.LogError(this.name + " has no MenuSystem component attached.");
            }
            if (this.GetComponent <Dialog>() == null)
            {
                ACDebug.LogError(this.name + " has no Dialog component attached.");
            }
            if (this.GetComponent <PlayerInput>() == null)
            {
                ACDebug.LogError(this.name + " has no PlayerInput component attached.");
            }
            if (this.GetComponent <PlayerInteraction>() == null)
            {
                ACDebug.LogError(this.name + " has no PlayerInteraction component attached.");
            }
            if (this.GetComponent <PlayerMovement>() == null)
            {
                ACDebug.LogError(this.name + " has no PlayerMovement component attached.");
            }
            if (this.GetComponent <PlayerCursor>() == null)
            {
                ACDebug.LogError(this.name + " has no PlayerCursor component attached.");
            }
            if (this.GetComponent <PlayerQTE>() == null)
            {
                ACDebug.LogError(this.name + " has no PlayerQTE component attached.");
            }
            if (this.GetComponent <SceneSettings>() == null)
            {
                ACDebug.LogError(this.name + " has no SceneSettings component attached.");
            }
            else
            {
                if (this.GetComponent <SceneSettings>().navigationMethod == AC_NavigationMethod.meshCollider && this.GetComponent <SceneSettings>().navMesh == null)
                {
                    // No NavMesh, are there Characters in the scene?
                    AC.Char[] allChars = GameObject.FindObjectsOfType(typeof(AC.Char)) as AC.Char[];
                    if (allChars.Length > 0)
                    {
                        ACDebug.LogWarning("No NavMesh set. Characters will not be able to PathFind until one is defined - please choose one using the Scene Manager.");
                    }
                }

                if (this.GetComponent <SceneSettings>().defaultPlayerStart == null)
                {
                    if (AdvGame.GetReferences().settingsManager == null || AdvGame.GetReferences().settingsManager.GetDefaultPlayer() != null)
                    {
                        ACDebug.LogWarning("No default PlayerStart set.  The game may not be able to begin if one is not defined - please choose one using the Scene Manager.");
                    }
                }
            }
            if (this.GetComponent <NavigationManager>() == null)
            {
                ACDebug.LogError(this.name + " has no NavigationManager component attached.");
            }
            if (this.GetComponent <ActionListManager>() == null)
            {
                ACDebug.LogError(this.name + " has no ActionListManager component attached.");
            }
            if (this.GetComponent <EventManager>() == null)
            {
                ACDebug.LogError(this.name + " has no EventManager component attached.");
            }
        }
        override public float Run()
        {
            if (KickStarter.speechManager == null)
            {
                ACDebug.Log("No Speech Manager present");
                return(0f);
            }

            if (KickStarter.dialog && KickStarter.stateHandler)
            {
                if (!isRunning)
                {
                    EventManager.OnClickConversation += GetChoiceID;
                    EventManager.OnStartSpeech       += SpeechStart;
                    EventManager.OnStopSpeech        += SpeechStop;
                    isRunning = true;
                    SetScript();
                    return(defaultPauseTime);
                }
                else
                {
                    if (evaluatingTags)
                    {
                        float t = EvaluateTags();

                        if (t > actionComplete)
                        {
                            return(t);
                        }
                        evaluatingTags = false;
                        return(defaultPauseTime);
                    }
                    if (ACInkIntegration.inkStory.canContinue && currentLine == string.Empty)
                    {
                        if (speech == null || !speech.isAlive)
                        {
                            if (tagIndex == -1)
                            {
                                currentLine = ACInkIntegration.inkStory.Continue();
                                tagIndex    = 0;
                                if (ACInkIntegration.inkStory.currentTags.Count > 0 && !evaluatingTags)
                                {
                                    evaluatingTags = true;
                                    return(defaultPauseTime);
                                }
                            }
                        }
                        CheckSpeechAudioEnded();
                        return(defaultPauseTime);
                    }

                    CheckSpeechAudioEnded();

                    if (speech != null)
                    {
                        if (speech.isAlive)
                        {
                            return(defaultPauseTime);
                        }
                    }

                    if (currentLine != string.Empty)
                    {
                        RunScript(currentLine);
                        tagIndex    = -1;
                        currentLine = string.Empty;
                        return(defaultPauseTime);
                    }

                    if (!conversation.IsActive(false) && choiceID >= 0)
                    {
                        ACInkIntegration.inkStory.ChooseChoiceIndex(choiceID);
                        choiceID = -1;
                        tagIndex = -1;
                        return(defaultPauseTime);
                    }

                    if (ACInkIntegration.inkStory.currentChoices.Count > 0 && !conversation.IsActive(false))
                    {
                        GetChoices();
                        conversation.Interact();
                    }

                    if (conversation != null && conversation.IsActive(false))
                    {
                        return(defaultPauseTime);
                    }

                    isRunning = false;
                    EventManager.OnClickConversation -= GetChoiceID;
                    EventManager.OnStartSpeech       -= SpeechStart;
                    EventManager.OnStopSpeech        -= SpeechStop;
                    return(0f);
                }
            }
            return(0f);
        }
        override public float Run()
        {
            if (!isRunning)
            {
                isRunning = true;

                if (faceObject == null && (faceType == CharFaceType.Body || (faceType == CharFaceType.Head && !stopLooking)))
                {
                    return(0f);
                }

                if (charToMove)
                {
                    if (faceType == CharFaceType.Body)
                    {
                        if (!isInstant && charToMove.IsMovingAlongPath())
                        {
                            charToMove.EndPath();
                        }

                        if (lookUpDown && isPlayer && KickStarter.settingsManager.IsInFirstPerson())
                        {
                            Player player = (Player)charToMove;
                            player.SetTilt(faceObject.transform.position, isInstant);
                        }

                        charToMove.SetLookDirection(GetLookVector(KickStarter.settingsManager), isInstant);
                    }
                    else if (faceType == CharFaceType.Head)
                    {
                        if (stopLooking)
                        {
                            charToMove.ClearHeadTurnTarget(isInstant, HeadFacing.Manual);
                        }
                        else
                        {
                            Vector3 offset = Vector3.zero;

                            Hotspot faceObjectHotspot = faceObject.GetComponent <Hotspot>();
                            Char    faceObjectChar    = faceObject.GetComponent <Char>();

                            if (lookAtHead && faceObjectChar != null)
                            {
                                Transform neckBone = faceObjectChar.neckBone;
                                if (neckBone != null)
                                {
                                    faceObject = neckBone.gameObject;
                                }
                                else
                                {
                                    ACDebug.Log("Cannot look at " + faceObjectChar.name + "'s head as their 'Neck bone' has not been defined.", faceObjectChar);
                                }
                            }
                            else if (faceObjectHotspot != null)
                            {
                                if (faceObjectHotspot.centrePoint != null)
                                {
                                    faceObject = faceObjectHotspot.centrePoint.gameObject;
                                }
                                else
                                {
                                    offset = faceObjectHotspot.GetIconPosition(true);
                                }
                            }

                            charToMove.SetHeadTurnTarget(faceObject.transform, offset, isInstant);
                        }
                    }

                    if (isInstant)
                    {
                        return(0f);
                    }
                    else
                    {
                        if (willWait)
                        {
                            return(defaultPauseTime);
                        }
                        else
                        {
                            return(0f);
                        }
                    }
                }

                return(0f);
            }
            else
            {
                if (faceType == CharFaceType.Head && charToMove.IsMovingHead())
                {
                    return(defaultPauseTime);
                }
                else if (faceType == CharFaceType.Body && charToMove.IsTurning())
                {
                    return(defaultPauseTime);
                }
                else
                {
                    isRunning = false;
                    return(0f);
                }
            }
        }
示例#16
0
        /**
         * Assigns its various Manager asset files.
         */
        public void AssignManagers()
        {
            if (AdvGame.GetReferences() != null)
            {
                int numAssigned = 0;

                if (sceneManager)
                {
                    AdvGame.GetReferences().sceneManager = sceneManager;
                    numAssigned++;
                }

                if (settingsManager)
                {
                    AdvGame.GetReferences().settingsManager = settingsManager;
                    numAssigned++;
                }

                if (actionsManager)
                {
                    AdvGame.GetReferences().actionsManager = actionsManager;
                    numAssigned++;
                }

                if (variablesManager)
                {
                    AdvGame.GetReferences().variablesManager = variablesManager;
                    numAssigned++;
                }

                if (inventoryManager)
                {
                    AdvGame.GetReferences().inventoryManager = inventoryManager;
                    numAssigned++;
                }

                if (speechManager)
                {
                    AdvGame.GetReferences().speechManager = speechManager;
                    numAssigned++;
                }

                if (cursorManager)
                {
                    AdvGame.GetReferences().cursorManager = cursorManager;
                    numAssigned++;
                }

                if (menuManager)
                {
                    AdvGame.GetReferences().menuManager = menuManager;
                    numAssigned++;
                }

                                #if UNITY_EDITOR
                if (!Application.isPlaying)
                {
                    KickStarter.ClearManagerCache();
                }

                if (KickStarter.sceneManager)
                {
                    KickStarter.sceneManager.GetPrefabsInScene();
                }

                UnityVersionHandler.CustomSetDirty(AdvGame.GetReferences(), true);
                AssetDatabase.SaveAssets();
                                #endif

                if (this)
                {
                    if (numAssigned == 0)
                    {
                        ACDebug.Log(this.name + " No Mangers assigned.");
                    }
                    else if (numAssigned == 1)
                    {
                        ACDebug.Log(this.name + " - (" + numAssigned.ToString() + ") Manager assigned.", this);
                    }
                    else
                    {
                        ACDebug.Log(this.name + " - (" + numAssigned.ToString() + ") Managers assigned.", this);
                    }
                }
            }
            else
            {
                ACDebug.LogError("Can't assign managers - no References file found in Resources folder.");
            }
        }
示例#17
0
        override public float Run()
        {
            if (_gameObject == null)
            {
                return(0f);
            }

            if (invAction == InvAction.Add)
            {
                // Instantiate

                GameObject oldOb = AssignFile(constantID, _gameObject);
                if (_gameObject.activeInHierarchy || (oldOb != null && oldOb.activeInHierarchy))
                {
                    RememberTransform rememberTransform = oldOb.GetComponent <RememberTransform>();

                    if (rememberTransform != null && rememberTransform.saveScenePresence && rememberTransform.linkedPrefabID != 0)
                    {
                        // Bypass this check
                    }
                    else
                    {
                        ACDebug.LogWarning(gameObject.name + " won't be instantiated, as it is already present in the scene.");
                        return(0f);
                    }
                }

                Vector3    position = _gameObject.transform.position;
                Quaternion rotation = _gameObject.transform.rotation;

                if (positionRelativeTo != PositionRelativeTo.Nothing)
                {
                    float forward = _gameObject.transform.position.z;
                    float right   = _gameObject.transform.position.x;
                    float up      = _gameObject.transform.position.y;

                    if (positionRelativeTo == PositionRelativeTo.RelativeToActiveCamera)
                    {
                        Transform mainCam = KickStarter.mainCamera.transform;
                        position              = mainCam.position + (mainCam.forward * forward) + (mainCam.right * right) + (mainCam.up * up);
                        rotation.eulerAngles += mainCam.transform.rotation.eulerAngles;
                    }
                    else if (positionRelativeTo == PositionRelativeTo.RelativeToPlayer)
                    {
                        if (KickStarter.player)
                        {
                            Transform playerTranform = KickStarter.player.transform;
                            position              = playerTranform.position + (playerTranform.forward * forward) + (playerTranform.right * right) + (playerTranform.up * up);
                            rotation.eulerAngles += playerTranform.rotation.eulerAngles;
                        }
                    }
                    else if (positionRelativeTo == PositionRelativeTo.RelativeToGameObject)
                    {
                        if (relativeGameObject != null)
                        {
                            Transform relativeTransform = relativeGameObject.transform;
                            position              = relativeTransform.position + (relativeTransform.forward * forward) + (relativeTransform.right * right) + (relativeTransform.up * up);
                            rotation.eulerAngles += relativeTransform.rotation.eulerAngles;
                        }
                    }
                    else if (positionRelativeTo == PositionRelativeTo.EnteredValue)
                    {
                        position += relativeVector;
                    }
                    else if (positionRelativeTo == PositionRelativeTo.VectorVariable)
                    {
                        if (variableLocation == VariableLocation.Global)
                        {
                            position += GlobalVariables.GetVector3Value(vectorVarID);
                        }
                        else if (variableLocation == VariableLocation.Local && !isAssetFile)
                        {
                            position += LocalVariables.GetVector3Value(vectorVarID);
                        }
                    }
                }

                GameObject newObject = (GameObject)Instantiate(_gameObject, position, rotation);
                newObject.name = _gameObject.name;

                if (newObject.GetComponent <RememberTransform>())
                {
                    newObject.GetComponent <RememberTransform>().OnSpawn();
                }

                KickStarter.stateHandler.IgnoreNavMeshCollisions();
            }
            else if (invAction == InvAction.Remove)
            {
                // Delete
                KickStarter.sceneChanger.ScheduleForDeletion(_gameObject);
            }
            else if (invAction == InvAction.Replace)
            {
                if (replaceGameObject == null)
                {
                    ACDebug.LogWarning("Cannot perform swap because the object to remove was not found in the scene.");
                    return(0f);
                }

                Vector3    position = replaceGameObject.transform.position;
                Quaternion rotation = replaceGameObject.transform.rotation;

                GameObject oldOb = AssignFile(constantID, _gameObject);
                if (gameObject.activeInHierarchy || (oldOb != null && oldOb.activeInHierarchy))
                {
                    ACDebug.Log(gameObject.name + " won't be instantiated, as it is already present in the scene.");
                    return(0f);
                }

                KickStarter.sceneChanger.ScheduleForDeletion(replaceGameObject);

                GameObject newObject = (GameObject)Instantiate(_gameObject, position, rotation);
                newObject.name = _gameObject.name;
                KickStarter.stateHandler.IgnoreNavMeshCollisions();
            }

            return(0f);
        }
示例#18
0
        override public float Run()
        {
            if (KickStarter.speechManager == null)
            {
                ACDebug.Log("No Speech Manager present");
                return(0f);
            }

            if (KickStarter.dialog && KickStarter.stateHandler)
            {
                if (!isRunning)
                {
                    stopAction = false;
                    isRunning  = true;
                    splitDelay = false;
                    splitIndex = 0;

                    endTime = Time.time + StartSpeech();

                    if (isBackground)
                    {
                        isRunning = false;
                        return(0f);
                    }
                    return(defaultPauseTime);
                }
                else
                {
                    if (stopAction || (speech != null && speech.continueFromSpeech))
                    {
                        speech.continueFromSpeech = false;
                        isRunning = false;
                        return(0);
                    }

                    if (speech == null || !speech.isAlive)
                    {
                        if (KickStarter.speechManager.separateLines)
                        {
                            if (!splitDelay)
                            {
                                // Begin pause if more lines are present
                                splitIndex++;
                                string[] textArray = messageText.Split(stringSeparators, System.StringSplitOptions.None);

                                if (textArray.Length > splitIndex)
                                {
                                    // Still got more to go, so pause for a moment
                                    splitDelay = true;
                                    return(KickStarter.speechManager.separateLinePause);
                                }
                                // else finished
                            }
                            else
                            {
                                // Show next line
                                splitDelay = false;
                                endTime    = Time.time + StartSpeech();
                                return(defaultPauseTime);
                            }
                        }

                        if (waitTimeOffset <= 0f)
                        {
                            isRunning = false;
                            return(0f);
                        }
                        else
                        {
                            stopAction = true;
                            return(waitTimeOffset);
                        }
                    }
                    else
                    {
                        if ((!isBackground && KickStarter.speechManager.displayForever) || speech.IsPaused())
                        {
                            return(defaultPauseTime);
                        }

                        if (KickStarter.speechManager.separateLines)
                        {
                            return(defaultPauseTime);
                        }

                        if (!speech.HasPausing())
                        {
                            // Ignore this if we're using [wait] tokens
                            if (Time.time < endTime)
                            {
                                return(defaultPauseTime);
                            }
                            else
                            {
                                isRunning = false;
                                return(0f);
                            }
                        }
                    }
                }
            }

            return(0f);
        }
示例#19
0
        /**
         * <summary>The default Constructor.</summary>
         * <param name = "_speaker">The speaking character. If null, the line is considered a narration</param>
         * <param name = "_message">The subtitle text to display</param>
         * <param name = "lineID">The unique ID number of the line, as generated by the Speech Manager</param>
         * <param name = "_language">The currently-selected language</param>
         * <param name = "_isBackground">True if the line should play in the background, and not interrupt Actions or gameplay</param>
         * <param name = "_noAnimation">True if the speaking character should not play a talking animation</param>
         */
        public Speech(Char _speaker, string _message, int lineID, string _language, bool _isBackground, bool _noAnimation)
        {
            log.Clear();
            isBackground = _isBackground;

            if (_speaker)
            {
                speaker           = _speaker;
                speaker.isTalking = !_noAnimation;
                log.speakerName   = _speaker.name;

                if (_speaker.GetComponent <Player>())
                {
                    if (KickStarter.settingsManager.playerSwitching == PlayerSwitching.Allow || !KickStarter.speechManager.usePlayerRealName)
                    {
                        log.speakerName = "Player";
                    }
                }

                if (_speaker.GetComponent <Hotspot>())
                {
                    if (_speaker.GetComponent <Hotspot>().hotspotName != "")
                    {
                        log.speakerName = _speaker.GetComponent <Hotspot>().hotspotName;
                    }
                }

                _speaker.ClearExpression();

                if (!_noAnimation)
                {
                    if (KickStarter.speechManager.lipSyncMode == LipSyncMode.Off)
                    {
                        speaker.isLipSyncing = false;
                    }
                    else if (KickStarter.speechManager.lipSyncMode == LipSyncMode.Salsa2D || KickStarter.speechManager.lipSyncMode == LipSyncMode.FromSpeechText || KickStarter.speechManager.lipSyncMode == LipSyncMode.ReadPamelaFile || KickStarter.speechManager.lipSyncMode == LipSyncMode.ReadSapiFile || KickStarter.speechManager.lipSyncMode == LipSyncMode.ReadPapagayoFile)
                    {
                        speaker.StartLipSync(KickStarter.dialog.GenerateLipSyncShapes(KickStarter.speechManager.lipSyncMode, lineID, speaker.name, _language, _message));
                    }
                    else if (KickStarter.speechManager.lipSyncMode == LipSyncMode.RogoLipSync)
                    {
                        RogoLipSyncIntegration.Play(_speaker, speaker.name, lineID, _language);
                    }
                }
            }
            else
            {
                if (speaker)
                {
                    speaker.isTalking = false;
                }
                speaker         = null;
                log.speakerName = "Narrator";
            }

            _message = AdvGame.ConvertTokens(_message);
            _message = DetermineGaps(_message);
            if (speechGaps.Count > 0)
            {
                gapIndex = 0;
                foreach (SpeechGap gap in speechGaps)
                {
                    if (gap.expressionID < 0)
                    {
                        displayDuration += (float)gap.waitTime;
                    }
                }
            }
            else
            {
                gapIndex = -1;
            }

            if (lineID > -1)
            {
                log.lineID = lineID;
            }

            // Play sound and time displayDuration to it
            if (lineID > -1 && log.speakerName != "" && KickStarter.speechManager.searchAudioFiles)
            {
                AudioClip clipObj = null;

                if (KickStarter.speechManager.autoNameSpeechFiles)
                {
                    string fullFilename = "Speech/";
                    string filename     = KickStarter.speechManager.GetLineFilename(lineID);
                    if (_language != "" && KickStarter.speechManager.translateAudio)
                    {
                        // Not in original language
                        fullFilename += _language + "/";
                    }
                    if (KickStarter.speechManager.placeAudioInSubfolders)
                    {
                        fullFilename += filename + "/";
                    }
                    fullFilename += filename + lineID;

                    clipObj = Resources.Load(fullFilename) as AudioClip;

                    if (clipObj == null)
                    {
                        ACDebug.Log("Cannot find audio file: " + fullFilename);
                    }
                }
                else
                {
                    clipObj = KickStarter.speechManager.GetLineCustomAudioClip(lineID, Options.GetLanguage());
                }

                if (clipObj)
                {
                    AudioSource audioSource = null;

                    if (_speaker != null)
                    {
                        if (!_noAnimation)
                        {
                            if (KickStarter.speechManager.lipSyncMode == LipSyncMode.FaceFX)
                            {
                                FaceFXIntegration.Play(speaker, log.speakerName + lineID, clipObj);
                            }
                        }

                        if (_speaker.speechAudioSource)
                        {
                            audioSource = _speaker.speechAudioSource;

                            if (_speaker.speechAudioSource.GetComponent <Sound>())
                            {
                                _speaker.speechAudioSource.GetComponent <Sound>().SetVolume(Options.optionsData.speechVolume);
                            }
                            else
                            {
                                _speaker.speechAudioSource.volume = Options.optionsData.speechVolume;
                            }
                        }
                        else
                        {
                            ACDebug.LogWarning(_speaker.name + " has no audio source component!");
                        }
                    }
                    else if (KickStarter.player && KickStarter.player.speechAudioSource)
                    {
                        KickStarter.player.speechAudioSource.volume = Options.optionsData.speechVolume;
                        audioSource = KickStarter.player.speechAudioSource;
                    }
                    else
                    {
                        audioSource = KickStarter.dialog.GetDefaultAudioSource();
                    }

                    if (audioSource != null)
                    {
                        audioSource.clip = clipObj;
                        audioSource.loop = false;
                        audioSource.Play();
                        hasAudio = true;
                    }

                    displayDuration = clipObj.length;
                }
                else
                {
                    displayDuration += KickStarter.speechManager.screenTimeFactor * (float)_message.Length;
                    if (displayDuration < 0.5f)
                    {
                        displayDuration = 0.5f;
                    }
                }
            }
            else
            {
                displayDuration += KickStarter.speechManager.screenTimeFactor * (float)_message.Length;
                if (displayDuration < 0.5f)
                {
                    displayDuration = 0.5f;
                }
            }

            log.fullText = _message;

            if (!CanScroll())
            {
                if (continueIndex > 0)
                {
                    continueTime = (continueIndex / KickStarter.speechManager.textScrollSpeed);
                }

                if (speechGaps.Count > 0)
                {
                    displayText = log.fullText.Substring(0, speechGaps[0].characterIndex);
                }
                else
                {
                    displayText = log.fullText;
                }
            }
            else
            {
                displayText = "";
            }

            isAlive     = true;
            isSkippable = true;
            pauseGap    = false;
            endTime     = displayDuration;
        }
        override public float Run()
        {
            if (KickStarter.speechManager == null)
            {
                ACDebug.Log("No Speech Manager present");
                return(0f);
            }

            if (KickStarter.dialog && KickStarter.stateHandler)
            {
                if (!isRunning)
                {
                    stopAction = false;
                    isRunning  = true;
                    splitDelay = false;
                    splitIndex = 0;

                    StartSpeech();

                    if (isBackground)
                    {
                        if (KickStarter.speechManager.separateLines)
                        {
                            string[] textArray = messageText.Split(stringSeparators, System.StringSplitOptions.None);
                            if (textArray != null && textArray.Length > 1)
                            {
                                ACDebug.LogWarning("Cannot separate multiple speech lines when 'Is Background?' is checked - will only play '" + textArray[0] + "'");
                            }
                        }

                        isRunning = false;
                        return(0f);
                    }
                    return(defaultPauseTime);
                }
                else
                {
                    if (stopAction || (speech != null && speech.continueFromSpeech))
                    {
                        speech.continueFromSpeech = false;
                        isRunning = false;

                        return(0);
                    }

                    if (speech == null || !speech.isAlive)
                    {
                        if (KickStarter.speechManager.separateLines)
                        {
                            if (!splitDelay)
                            {
                                // Begin pause if more lines are present
                                splitIndex++;
                                string[] textArray = messageText.Split(stringSeparators, System.StringSplitOptions.None);

                                if (textArray.Length > splitIndex)
                                {
                                    if (KickStarter.speechManager.separateLinePause > 0f)
                                    {
                                        // Still got more to go
                                        splitDelay = true;
                                        return(KickStarter.speechManager.separateLinePause);
                                    }
                                    else
                                    {
                                        // Show next line
                                        splitDelay = false;
                                        StartSpeech();
                                        return(defaultPauseTime);
                                    }
                                }
                                // else finished
                            }
                            else
                            {
                                // Show next line
                                splitDelay = false;
                                StartSpeech();
                                return(defaultPauseTime);
                            }
                        }

                        if (waitTimeOffset <= 0f)
                        {
                            isRunning = false;
                            return(0f);
                        }
                        else
                        {
                            stopAction = true;
                            return(waitTimeOffset);
                        }
                    }
                    else
                    {
                        return(defaultPauseTime);
                    }
                }
            }

            return(0f);
        }
        override public float Run()
        {
            if (KickStarter.settingsManager.playerSwitching == PlayerSwitching.Allow)
            {
                if (KickStarter.sceneChanger.GetSubScenes().Length > 0)
                {
                    //	ACDebug.LogWarning ("Cannot switch players while multiple scenes are open!");
                    //	return 0f;
                }

                if (KickStarter.settingsManager.players.Count > 0 && KickStarter.settingsManager.players.Count > playerNumber && playerNumber > -1)
                {
                    if (KickStarter.player != null && KickStarter.player.ID == playerID)
                    {
                        ACDebug.Log("Cannot switch player - already controlling the desired prefab.");
                        return(0f);
                    }

                    if (KickStarter.settingsManager.players[playerNumber].playerOb != null)
                    {
                        KickStarter.saveSystem.SaveCurrentPlayerData();

                        Vector3    oldPlayerPosition = Vector3.zero;
                        Quaternion oldPlayerRotation = new Quaternion();
                        Vector3    oldPlayerScale    = Vector3.one;

                        if (KickStarter.player != null)
                        {
                            oldPlayerPosition = KickStarter.player.transform.position;
                            oldPlayerRotation = KickStarter.player.transform.rotation;
                            oldPlayerScale    = KickStarter.player.transform.localScale;
                        }

                        if (oldPlayer == OldPlayer.ReplaceWithNPC && oldPlayerNPC != null &&
                            (newPlayerPosition == NewPlayerPosition.ReplaceNPC || newPlayerPosition == NewPlayerPosition.AppearAtMarker))
                        {
                            oldPlayerNPC.transform.position   = oldPlayerPosition;
                            oldPlayerNPC.transform.rotation   = oldPlayerRotation;
                            oldPlayerNPC.transform.localScale = oldPlayerScale;
                        }

                        Quaternion newRotation = Quaternion.identity;
                        if (newPlayerPosition == NewPlayerPosition.ReplaceCurrentPlayer)
                        {
                            newRotation = oldPlayerRotation;
                        }
                        else if (newPlayerPosition == NewPlayerPosition.ReplaceNPC && newPlayerNPC)
                        {
                            newRotation = newPlayerNPC.transform.rotation;
                        }
                        else if (newPlayerPosition == NewPlayerPosition.AppearAtMarker && newPlayerMarker)
                        {
                            newRotation = newPlayerMarker.transform.rotation;
                        }

                        KickStarter.ResetPlayer(KickStarter.settingsManager.players[playerNumber].playerOb, playerID, true, newRotation, keepInventory);
                        Player newPlayer = KickStarter.player;
                        PlayerMenus.ResetInventoryBoxes();

                        if (restorePreviousData && KickStarter.saveSystem.DoesPlayerDataExist(playerID, true))
                        {
                            int sceneToLoad = KickStarter.saveSystem.GetPlayerScene(playerID);
                            if (sceneToLoad >= 0 && sceneToLoad != UnityVersionHandler.GetCurrentSceneNumber())
                            {
                                KickStarter.saveSystem.loadingGame = LoadingGame.JustSwitchingPlayer;
                                KickStarter.sceneChanger.ChangeScene(new SceneInfo("", sceneToLoad), true);
                            }
                            else
                            {
                                string sceneToLoadName = KickStarter.saveSystem.GetPlayerSceneName(playerID);
                                if (sceneToLoadName != "" && sceneToLoadName != UnityVersionHandler.GetCurrentSceneName())
                                {
                                    KickStarter.saveSystem.loadingGame = LoadingGame.JustSwitchingPlayer;
                                    KickStarter.sceneChanger.ChangeScene(new SceneInfo(sceneToLoadName, -1), true);
                                }
                            }

                            /*int sceneToLoad = KickStarter.saveSystem.GetPlayerScene (playerID);
                             * string sceneToLoadName = KickStarter.saveSystem.GetPlayerSceneName (playerID);
                             *
                             * if (sceneToLoad != UnityVersionHandler.GetCurrentSceneNumber ())
                             * {
                             *      KickStarter.saveSystem.loadingGame = LoadingGame.JustSwitchingPlayer;
                             *      KickStarter.sceneChanger.ChangeScene (new SceneInfo (sceneToLoadName, sceneToLoad), true);
                             * }*/
                        }
                        else
                        {
                            if (newPlayerPosition == NewPlayerPosition.ReplaceCurrentPlayer)
                            {
                                newPlayer.Teleport(oldPlayerPosition);
                                newPlayer.SetRotation(oldPlayerRotation);
                                newPlayer.transform.localScale = oldPlayerScale;
                            }
                            else if (newPlayerPosition == NewPlayerPosition.ReplaceNPC)
                            {
                                if (newPlayerNPC)
                                {
                                    newPlayer.Teleport(newPlayerNPC.transform.position);
                                    newPlayer.SetRotation(newPlayerNPC.transform.rotation);
                                    newPlayer.transform.localScale = newPlayerNPC.transform.localScale;

                                    newPlayerNPC.transform.position += new Vector3(100f, -100f, 100f);
                                }
                            }
                            else if (newPlayerPosition == NewPlayerPosition.AppearAtMarker)
                            {
                                if (newPlayerMarker)
                                {
                                    newPlayer.Teleport(newPlayerMarker.transform.position);
                                    newPlayer.SetRotation(newPlayerMarker.transform.rotation);
                                    newPlayer.transform.localScale = newPlayerMarker.transform.localScale;
                                }
                            }
                            else if (newPlayerPosition == NewPlayerPosition.AppearInOtherScene)
                            {
                                if (chooseNewSceneBy == ChooseSceneBy.Name && newPlayerSceneName == UnityVersionHandler.GetCurrentSceneName())
                                {
                                }
                                else if (chooseNewSceneBy == ChooseSceneBy.Number && newPlayerScene == UnityVersionHandler.GetCurrentSceneNumber())
                                {
                                }
                                else
                                {
                                    KickStarter.sceneChanger.ChangeScene(new SceneInfo(chooseNewSceneBy, newPlayerSceneName, newPlayerScene), true);
                                }
                            }
                        }

                        if (KickStarter.mainCamera.attachedCamera)
                        {
                            KickStarter.mainCamera.attachedCamera.MoveCameraInstant();
                        }

                        AssetLoader.UnloadAssets();
                    }
                    else
                    {
                        ACDebug.LogWarning("Cannot switch player - no player prefabs is defined.");
                    }
                }
            }

            return(0f);
        }
示例#22
0
        /**
         * <summary>Adds a ConstantID component to a GameObject, which can be a prefab or a scene-based object</summary>
         * <param name = "gameObject">The GameObject to amend</param>
         * <returns>The GameObject's component</returns>
         */
        public static T AddConstantIDToGameObject <T> (GameObject gameObject, bool forcePrefab = false) where T : ConstantID
        {
            T existingComponent = gameObject.GetComponent <T>();

            if (existingComponent != null)
            {
                if (existingComponent.constantID == 0)
                {
                                        #if NEW_PREFABS
                    if (IsPrefabFile(gameObject) && !IsPrefabEditing(gameObject))
                    {
                        string     assetPath       = AssetDatabase.GetAssetPath(gameObject);
                        GameObject instancedObject = PrefabUtility.LoadPrefabContents(assetPath);
                        instancedObject.GetComponent <ConstantID>().AssignInitialValue(true);
                        PrefabUtility.SaveAsPrefabAsset(instancedObject, assetPath);
                        PrefabUtility.UnloadPrefabContents(instancedObject);
                    }
                    else
                    {
                        existingComponent.AssignInitialValue(forcePrefab);
                    }
                                        #else
                    existingComponent.AssignInitialValue(forcePrefab);
                                        #endif
                }

                CustomSetDirty(gameObject, true);
                if (IsPrefabFile(gameObject))
                {
                    AssetDatabase.SaveAssets();
                }

                return(existingComponent);
            }

                        #if NEW_PREFABS
            if (UnityVersionHandler.IsPrefabFile(gameObject) && !IsPrefabEditing(gameObject))
            {
                string     assetPath       = AssetDatabase.GetAssetPath(gameObject);
                GameObject instancedObject = PrefabUtility.LoadPrefabContents(assetPath);
                existingComponent = instancedObject.AddComponent <T>();
                existingComponent.AssignInitialValue(true);

                foreach (ConstantID constantIDScript in instancedObject.GetComponents <ConstantID>())
                {
                    if (!(constantIDScript is Remember) && !(constantIDScript is RememberTransform) && constantIDScript != existingComponent)
                    {
                        GameObject.DestroyImmediate(constantIDScript, true);
                        ACDebug.Log("Replaced " + gameObject.name + "'s 'ConstantID' component with '" + existingComponent.GetType().ToString() + "'", gameObject);
                    }
                }

                PrefabUtility.SaveAsPrefabAsset(instancedObject, assetPath);
                PrefabUtility.UnloadPrefabContents(instancedObject);

                CustomSetDirty(gameObject, true);
                AssetDatabase.SaveAssets();

                return(existingComponent);
            }
                        #endif

            existingComponent = gameObject.AddComponent <T>();
            existingComponent.AssignInitialValue(forcePrefab);

            foreach (ConstantID constantIDScript in gameObject.GetComponents <ConstantID>())
            {
                if (!(constantIDScript is Remember) && !(constantIDScript is RememberTransform) && constantIDScript != existingComponent)
                {
                    GameObject.DestroyImmediate(constantIDScript, true);
                    ACDebug.Log("Replaced " + gameObject.name + "'s 'ConstantID' component with '" + existingComponent.GetType().ToString() + "'", gameObject);
                }
            }

            CustomSetDirty(gameObject, true);
            if (IsPrefabFile(gameObject))
            {
                AssetDatabase.SaveAssets();
            }

            return(existingComponent);
        }
示例#23
0
        private void Export()
        {
                        #if UNITY_WEBPLAYER
            ACDebug.LogWarning("Game text cannot be exported in WebPlayer mode - please switch platform and try again.");
                        #else
            if (speechManager == null || exportColumns == null || exportColumns.Count == 0 || speechManager.lines == null || speechManager.lines.Count == 0)
            {
                return;
            }

            string suggestedFilename = string.Empty;
            if (AdvGame.GetReferences().settingsManager)
            {
                suggestedFilename = AdvGame.GetReferences().settingsManager.saveFileName + " - ";
            }
            suggestedFilename += "GameText.csv";

            string fileName = EditorUtility.SaveFilePanel("Export game text", "Assets", suggestedFilename, "csv");
            if (fileName.Length == 0)
            {
                return;
            }

            List <SpeechLine> exportLines = new List <SpeechLine>();
            foreach (SpeechLine line in speechManager.lines)
            {
                if (filterByType)
                {
                    if (line.textType != typeFilter)
                    {
                        continue;
                    }
                }
                if (filterByScene)
                {
                    if (sceneNames != null && sceneNames.Length > sceneFilter)
                    {
                        string selectedScene      = sceneNames[sceneFilter] + ".unity";
                        string scenePlusExtension = (string.IsNullOrEmpty(line.scene)) ? string.Empty : (line.scene + ".unity");

                        if ((string.IsNullOrEmpty(line.scene) && sceneFilter == 0) ||
                            sceneFilter == 1 ||
                            (!string.IsNullOrEmpty(line.scene) && sceneFilter > 1 && line.scene.EndsWith(selectedScene)) ||
                            (!string.IsNullOrEmpty(line.scene) && sceneFilter > 1 && scenePlusExtension.EndsWith(selectedScene)))
                        {
                        }
                        else
                        {
                            continue;
                        }
                    }
                }
                if (filterByText)
                {
                    if (!line.Matches(textFilter, filterSpeechLine))
                    {
                        continue;
                    }
                }
                if (filterByTag)
                {
                    if (tagFilter == -1 ||
                        (tagFilter < speechManager.speechTags.Count && line.tagID == speechManager.speechTags[tagFilter].ID))
                    {
                    }
                    else
                    {
                        continue;
                    }
                }

                exportLines.Add(new SpeechLine(line));
            }

            if (doRowSorting)
            {
                switch (rowSorting)
                {
                case RowSorting.ByID:
                    exportLines.Sort((a, b) => a.lineID.CompareTo(b.lineID));
                    break;

                case RowSorting.ByDescription:
                    exportLines.Sort((a, b) => string.Compare(a.description, b.description, System.StringComparison.Ordinal));
                    break;

                case RowSorting.ByType:
                    exportLines.Sort((a, b) => string.Compare(a.textType.ToString(), b.textType.ToString(), System.StringComparison.Ordinal));
                    break;

                case RowSorting.ByAssociatedObject:
                    exportLines.Sort((a, b) => string.Compare(a.owner, b.owner, System.StringComparison.Ordinal));
                    break;

                case RowSorting.ByScene:
                    exportLines.Sort((a, b) => string.Compare(a.scene, b.scene, System.StringComparison.Ordinal));
                    break;

                default:
                    break;
                }
            }

            List <string[]> output = new List <string[]>();

            string[]      languagesArray = speechManager.languages.ToArray();
            List <string> headerList     = new List <string>();
            headerList.Add("ID");
            foreach (ExportColumn exportColumn in exportColumns)
            {
                headerList.Add(exportColumn.GetHeader(languagesArray));
            }
            output.Add(headerList.ToArray());

            foreach (SpeechLine line in exportLines)
            {
                List <string> rowList = new List <string>();
                rowList.Add(line.lineID.ToString());
                foreach (ExportColumn exportColumn in exportColumns)
                {
                    string cellText = exportColumn.GetCellText(line);
                    rowList.Add(cellText);
                }
                output.Add(rowList.ToArray());
            }

            string fileContents = CSVReader.CreateCSVGrid(output);
            if (!string.IsNullOrEmpty(fileContents) && Serializer.SaveFile(fileName, fileContents))
            {
                int numLines = exportLines.Count;
                ACDebug.Log(numLines.ToString() + " line" + ((numLines != 1) ? "s" : string.Empty) + " exported.");
            }
                        #endif
        }
示例#24
0
        /**
         * Assigns its various Manager asset files.
         */
        public void AssignManagers()
        {
            if (AdvGame.GetReferences() != null)
            {
                if (sceneManager)
                {
                    AdvGame.GetReferences().sceneManager = sceneManager;
                }

                if (settingsManager)
                {
                    AdvGame.GetReferences().settingsManager = settingsManager;
                }

                if (actionsManager)
                {
                    AdvGame.GetReferences().actionsManager = actionsManager;
                }

                if (variablesManager)
                {
                    AdvGame.GetReferences().variablesManager = variablesManager;
                }

                if (inventoryManager)
                {
                    AdvGame.GetReferences().inventoryManager = inventoryManager;
                }

                if (speechManager)
                {
                    AdvGame.GetReferences().speechManager = speechManager;
                }

                if (cursorManager)
                {
                    AdvGame.GetReferences().cursorManager = cursorManager;
                }

                if (menuManager)
                {
                    AdvGame.GetReferences().menuManager = menuManager;
                }

                                #if UNITY_EDITOR
                if (KickStarter.sceneManager)
                {
                    KickStarter.sceneManager.GetPrefabsInScene();
                }

                AssetDatabase.SaveAssets();
                                #endif

                if (this)
                {
                    ACDebug.Log(this.name + " - Managers assigned.");
                }
            }
            else
            {
                ACDebug.LogError("Can't assign managers - no References file found in Resources folder.");
            }
        }
示例#25
0
        private IEnumerator RunAction(Action action)
        {
            action.AssignParentList(this);
            if (useParameters)
            {
                action.AssignValues(parameters);
            }
            else
            {
                action.AssignValues(null);
            }

            if (isSkipping)
            {
                skipIteractions++;
                action.Skip();

                if (KickStarter.settingsManager.printActionCommentsInConsole)
                {
                    action.PrintComment(this);
                }
            }
            else
            {
                if (action is ActionRunActionList)
                {
                    ActionRunActionList actionRunActionList = (ActionRunActionList)action;
                    actionRunActionList.isSkippable = IsSkippable();
                }

                if (isChangingScene)
                {
                    ACDebug.Log("Cannot begin Action #" + actions.IndexOf(action) + " " + action.category + ": " + action.title + " in list " + gameObject.name + " while changing scene, will resume once loading is complete.", this);
                    while (isChangingScene)
                    {
                        yield return(null);
                    }
                }

                action.isRunning = false;
                float waitTime = action.Run();

                if (KickStarter.settingsManager.printActionCommentsInConsole)
                {
                    action.PrintComment(this);
                }

                if (action is ActionParallel)
                {
                }
                else if (!Mathf.Approximately(waitTime, 0f))
                {
                    while (action.isRunning)
                    {
                        bool runInRealtime = (this is RuntimeActionList && actionListType == ActionListType.PauseGameplay && !unfreezePauseMenus && KickStarter.playerMenus.ArePauseMenusOn(null));

                        if (isChangingScene)
                        {
                            ACDebug.Log("Cannot continue Action #" + actions.IndexOf(action) + " " + action.category + ": " + action.title + " in list " + gameObject.name + " while changing scene, will resume once loading is complete.", this);
                            while (isChangingScene)
                            {
                                yield return(null);
                            }
                        }

                        if (waitTime < 0)
                        {
                            if (!runInRealtime && Time.timeScale <= 0f)
                            {
                                while (Time.timeScale <= 0f)
                                {
                                    yield return(new WaitForEndOfFrame());
                                }
                            }
                            else
                            {
                                yield return(new WaitForEndOfFrame());
                            }
                        }
                        else if (runInRealtime)
                        {
                            float endTime = Time.realtimeSinceStartup + waitTime;
                            while (Time.realtimeSinceStartup < endTime)
                            {
                                yield return(null);
                            }
                        }
                        else
                        {
                            yield return(new WaitForSeconds(waitTime));
                        }

                        if (!action.isRunning)
                        {
                            // In rare cases (once an actionlist is reset) isRunning may be false but this while loop will still run
                            ResetList();
                            break;
                        }

                        waitTime = action.Run();
                    }
                }
            }

            if (action is ActionParallel)
            {
                EndActionParallel((ActionParallel)action);
            }
            else
            {
                EndAction(action);
            }
        }
示例#26
0
        private void RunOption(ButtonDialog _option)
        {
            KickStarter.actionListManager.SetCorrectGameState();

            _option.hasBeenChosen = true;
            if (options.Contains(_option))
            {
                lastOption = options.IndexOf(_option);
                if (KickStarter.actionListManager.OverrideConversation(lastOption))
                {
                    return;
                }
                lastOption = -1;
            }

            Conversation endConversation = null;

            if (interactionSource != InteractionSource.CustomScript)
            {
                if (_option.conversationAction == ConversationAction.ReturnToConversation)
                {
                    endConversation = this;
                }
                else if (_option.conversationAction == ConversationAction.RunOtherConversation && _option.newConversation != null)
                {
                    endConversation = _option.newConversation;
                }
            }

            if (interactionSource == InteractionSource.AssetFile && _option.assetFile)
            {
                AdvGame.RunActionListAsset(_option.assetFile, endConversation);
            }
            else if (interactionSource == InteractionSource.CustomScript)
            {
                if (_option.customScriptObject != null && _option.customScriptFunction != "")
                {
                    _option.customScriptObject.SendMessage(_option.customScriptFunction);
                }
            }
            else if (interactionSource == InteractionSource.InScene && _option.dialogueOption)
            {
                _option.dialogueOption.conversation = endConversation;
                _option.dialogueOption.Interact();
            }
            else
            {
                ACDebug.Log("No Interaction object found!");

                if (endConversation != null)
                {
                    endConversation.Interact();
                }
                else
                {
                    KickStarter.stateHandler.gameState = GameState.Normal;
                }
            }

            KickStarter.eventManager.Call_OnClickConversation(this, _option.ID);
        }
示例#27
0
        private void Export()
        {
                        #if UNITY_WEBPLAYER
            ACDebug.LogWarning("Game text cannot be exported in WebPlayer mode - please switch platform and try again.");
                        #else
            if (speechManager == null || exportColumns == null || exportColumns.Count == 0 || speechManager.lines == null || speechManager.lines.Count == 0)
            {
                return;
            }

            string suggestedFilename = string.Empty;
            if (AdvGame.GetReferences().settingsManager)
            {
                suggestedFilename = AdvGame.GetReferences().settingsManager.saveFileName + " - ";
            }
            suggestedFilename += "GameText.csv";

            string fileName = EditorUtility.SaveFilePanel("Export game text", "Assets", suggestedFilename, "csv");
            if (fileName.Length == 0)
            {
                return;
            }

            string[]          sceneNames  = speechManager.GetSceneNames();
            List <SpeechLine> exportLines = new List <SpeechLine>();
            foreach (SpeechLine line in speechManager.lines)
            {
                if (filterByType)
                {
                    if (line.textType != typeFilter)
                    {
                        continue;
                    }
                }
                if (filterByScene)
                {
                    if (sceneNames != null && sceneNames.Length > sceneFilter)
                    {
                        string selectedScene      = sceneNames[sceneFilter] + ".unity";
                        string scenePlusExtension = (string.IsNullOrEmpty(line.scene)) ? string.Empty : (line.scene + ".unity");

                        if ((string.IsNullOrEmpty(line.scene) && sceneFilter == 0) ||
                            sceneFilter == 1 ||
                            (!string.IsNullOrEmpty(line.scene) && sceneFilter > 1 && line.scene.EndsWith(selectedScene)) ||
                            (!string.IsNullOrEmpty(line.scene) && sceneFilter > 1 && scenePlusExtension.EndsWith(selectedScene)))
                        {
                        }
                        else
                        {
                            continue;
                        }
                    }
                }
                if (filterByText)
                {
                    if (!line.Matches(textFilter, filterSpeechLine))
                    {
                        continue;
                    }
                }
                if (filterByTag)
                {
                    if (tagFilter == -1 ||
                        (tagFilter < speechManager.speechTags.Count && line.tagID == speechManager.speechTags[tagFilter].ID))
                    {
                    }
                    else
                    {
                        continue;
                    }
                }

                exportLines.Add(new SpeechLine(line));
            }

            if (doRowSorting)
            {
                if (rowSorting == RowSorting.ByID)
                {
                    exportLines.Sort(delegate(SpeechLine a, SpeechLine b) { return(a.lineID.CompareTo(b.lineID)); });
                }
                else if (rowSorting == RowSorting.ByDescription)
                {
                    exportLines.Sort(delegate(SpeechLine a, SpeechLine b) { return(a.description.CompareTo(b.description)); });
                }
                else if (rowSorting == RowSorting.ByType)
                {
                    exportLines.Sort(delegate(SpeechLine a, SpeechLine b) { return(a.textType.ToString().CompareTo(b.textType.ToString())); });
                }
                else if (rowSorting == RowSorting.ByAssociatedObject)
                {
                    exportLines.Sort(delegate(SpeechLine a, SpeechLine b) { return(a.owner.CompareTo(b.owner)); });
                }
                else if (rowSorting == RowSorting.ByScene)
                {
                    exportLines.Sort(delegate(SpeechLine a, SpeechLine b) { return(a.scene.CompareTo(b.owner)); });
                }
            }

            bool            fail   = false;
            List <string[]> output = new List <string[]>();

            string[]      languagesArray = speechManager.languages.ToArray();
            List <string> headerList     = new List <string>();
            headerList.Add("ID");
            foreach (ExportColumn exportColumn in exportColumns)
            {
                headerList.Add(exportColumn.GetHeader(languagesArray));
            }
            output.Add(headerList.ToArray());

            foreach (SpeechLine line in exportLines)
            {
                List <string> rowList = new List <string>();
                rowList.Add(line.lineID.ToString());
                foreach (ExportColumn exportColumn in exportColumns)
                {
                    string cellText = exportColumn.GetCellText(line);
                    rowList.Add(cellText);

                    if (cellText.Contains(CSVReader.csvDelimiter))
                    {
                        fail = true;
                        ACDebug.LogError("Cannot export translation since line " + line.lineID.ToString() + " (" + line.text + ") contains the character '" + CSVReader.csvDelimiter + "'.");
                    }
                }
                output.Add(rowList.ToArray());
            }

            if (!fail)
            {
                int length = output.Count;

                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                for (int j = 0; j < length; j++)
                {
                    sb.AppendLine(string.Join(CSVReader.csvDelimiter, output[j]));
                }

                if (Serializer.SaveFile(fileName, sb.ToString()))
                {
                    int numLines = exportLines.Count;
                    ACDebug.Log(numLines.ToString() + " line" + ((numLines != 1) ? "s" : string.Empty) + " exported.");
                }
            }

            //this.Close ();
                        #endif
        }
示例#28
0
        // Layers

        private static bool IsLayerDefined(string layerName, bool addIfUndefined = false)
        {
            SerializedObject   tagManager = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/TagManager.asset")[0]);
            SerializedProperty allLayers  = tagManager.FindProperty("layers");

            if (allLayers == null || !allLayers.isArray)
            {
                return(false);
            }

            // Check if layer is present
            bool foundLayer = false;

            for (int i = 0; i <= 31; i++)
            {
                SerializedProperty sp = allLayers.GetArrayElementAtIndex(i);

                if (sp != null && layerName.Equals(sp.stringValue))
                {
                    foundLayer = true;
                    break;
                }
            }

            if (!addIfUndefined)
            {
                return(foundLayer);
            }

            if (foundLayer)
            {
                return(true);
            }

            // Create layer
            SerializedProperty slot = null;

            for (int i = 8; i <= 31; i++)
            {
                SerializedProperty sp = allLayers.GetArrayElementAtIndex(i);

                if (sp != null && string.IsNullOrEmpty(sp.stringValue))
                {
                    slot = sp;
                    break;
                }
            }

            if (slot != null)
            {
                slot.stringValue = layerName;
            }
            else
            {
                ACDebug.LogError("Could not find an open Layer Slot for: " + layerName);
                return(false);
            }

            tagManager.ApplyModifiedProperties();

            ACDebug.Log("Created layer: '" + layerName + "'");
            return(true);
        }
示例#29
0
        private void CleanUpAsset()
        {
            string assetPath = AssetDatabase.GetAssetPath(this);

            Object[] objects = AssetDatabase.LoadAllAssetsAtPath(assetPath);

            foreach (Object _object in objects)
            {
                if (_object is Menu)
                {
                    AC.Menu _menu = (Menu)_object;

                    bool found = false;
                    foreach (AC.Menu menu in menus)
                    {
                        if (menu == _menu)
                        {
                            _object.hideFlags = HideFlags.HideInHierarchy;
                            found             = true;
                            break;
                        }
                    }

                    if (!found)
                    {
                        ACDebug.Log("Deleted unset menu: " + _menu.title);
                        DestroyImmediate(_object, true);
                    }

                    for (int i = 0; i < _menu.elements.Count; i++)
                    {
                        if (_menu.elements[i] == null)
                        {
                            _menu.elements.RemoveAt(i);
                            i = 0;
                        }
                    }
                }
            }

            foreach (Object _object in objects)
            {
                if (_object is MenuElement)
                {
                    MenuElement _element = (MenuElement)_object;

                    bool found = false;
                    foreach (AC.Menu menu in menus)
                    {
                        foreach (MenuElement element in menu.elements)
                        {
                            if (element == _element)
                            {
                                _object.hideFlags = HideFlags.HideInHierarchy;
                                found             = true;
                                break;
                            }
                        }
                    }

                    if (!found)
                    {
                        ACDebug.Log("Deleted unset element: " + _element.title);
                        DestroyImmediate(_object, true);
                    }
                }
            }

            AssetDatabase.SaveAssets();
        }
        private void Export()
        {
                        #if UNITY_WEBPLAYER
            ACDebug.LogWarning("Game text cannot be exported in WebPlayer mode - please switch platform and try again.");
                        #else
            if (variablesManager == null || exportColumns == null || exportColumns.Count == 0)
            {
                return;
            }

            if (variableLocation == VariableLocation.Local && allScenes)
            {
                bool canProceed = EditorUtility.DisplayDialog("Export variables", "AC will now go through your game, and collect all variables to be exported.\n\nIt is recommended to back up your project beforehand.", "OK", "Cancel");
                if (!canProceed)
                {
                    return;
                }

                if (!UnityEditor.SceneManagement.EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo())
                {
                    return;
                }
            }

            string suggestedFilename = "";
            if (AdvGame.GetReferences().settingsManager)
            {
                suggestedFilename = AdvGame.GetReferences().settingsManager.saveFileName + " - ";
            }
            if (variableLocation == VariableLocation.Local && allScenes)
            {
                suggestedFilename += " All ";
            }
            suggestedFilename += variableLocation.ToString() + " Variables.csv";

            string fileName = EditorUtility.SaveFilePanel("Export variables", "Assets", suggestedFilename, "csv");
            if (fileName.Length == 0)
            {
                return;
            }

            List <string[]> output = new List <string[]>();

            List <string> headerList = new List <string>();
            headerList.Add("ID");
            foreach (ExportColumn exportColumn in exportColumns)
            {
                headerList.Add(exportColumn.GetHeader());
            }
            output.Add(headerList.ToArray());

            // Global
            if (variableLocation == VariableLocation.Global)
            {
                List <GVar> exportVars = new List <GVar>();
                foreach (GVar globalVariable in variablesManager.vars)
                {
                    exportVars.Add(new GVar(globalVariable));
                }

                foreach (GVar exportVar in exportVars)
                {
                    List <string> rowList = new List <string>();
                    rowList.Add(exportVar.id.ToString());
                    foreach (ExportColumn exportColumn in exportColumns)
                    {
                        string cellText = exportColumn.GetCellText(exportVar, VariableLocation.Global, replaceForwardSlashes);
                        rowList.Add(cellText);
                    }
                    output.Add(rowList.ToArray());
                }
            }

            // Local
            else if (variableLocation == VariableLocation.Local)
            {
                if (allScenes)
                {
                    string   originalScene = UnityVersionHandler.GetCurrentSceneFilepath();
                    string[] sceneFiles    = AdvGame.GetSceneFiles();
                    foreach (string sceneFile in sceneFiles)
                    {
                        UnityVersionHandler.OpenScene(sceneFile);

                        if (FindObjectOfType <LocalVariables>())
                        {
                            LocalVariables localVariables = FindObjectOfType <LocalVariables>();
                            if (localVariables != null)
                            {
                                string sceneName = UnityVersionHandler.GetCurrentSceneName();
                                output = GatherOutput(output, localVariables.localVars, sceneName);
                            }
                        }
                    }

                    if (string.IsNullOrEmpty(originalScene))
                    {
                        UnityVersionHandler.NewScene();
                    }
                    else
                    {
                        UnityVersionHandler.OpenScene(originalScene);
                    }
                }
                else
                {
                    string sceneName = UnityVersionHandler.GetCurrentSceneName();
                    output = GatherOutput(output, KickStarter.localVariables.localVars, sceneName);
                }
            }

            // Component
            else if (variableLocation == VariableLocation.Component)
            {
                string sceneName = UnityVersionHandler.GetCurrentSceneName();
                if (variables != null)
                {
                    output = GatherOutput(output, variables.vars, sceneName);
                }
            }

            string fileContents = CSVReader.CreateCSVGrid(output);
            if (!string.IsNullOrEmpty(fileContents) && Serializer.SaveFile(fileName, fileContents))
            {
                int numExported = output.Count - 1;
                if (numExported == 1)
                {
                    ACDebug.Log("1 " + variableLocation + " variable exported.");
                }
                else
                {
                    ACDebug.Log(numExported.ToString() + " " + variableLocation + " variables exported.");
                }
            }
                        #endif
        }