inkle / ink

inkle's open source scripting language for writing interactive narrative.
http://www.inklestudios.com/ink
MIT License
4.11k stars 491 forks source link

I can't save the story corretly #579

Open javasilk opened 4 years ago

javasilk commented 4 years ago

Hi all, I can't the story correctly. When I load the story that I saved before, I always go to the end of the story. I have updated the version of ink. Someone can help me?

using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using Ink.Runtime; using UnityEngine.UI; using DG.Tweening;

using Debug = UnityEngine.Debug;

public class GameState : MainState {

// The json compiled ink story
public TextAsset storyJSON;
// The ink runtime story object
private Story story;

public ContentManager contentManager;

public ContentView contentViewPrefab;
public ChoiceGroupView choiceGroupViewPrefab;
public ChevronButtonView chevronViewPrefab;
public EmptyView emptyViewPrefab;

public Transform contentParent;
public ChoiceGroupContainerView choiceContainerView;

public ScrollToBottomButtonView scrollToBottomButton;

public bool hasMadeAChoice = false;

public SettingsView settingsView;
public SettingsButton settingsButton;
public bool deleteStorySaved = false;

private void Awake () {
    contentManager.enabled = false;
    settingsView.Hide();
    settingsButton.Hide();
}

public override void Enter () {
    base.Enter ();
    contentManager.enabled = true;
    settingsButton.FadeIn();

    if(storyJSON == null) {
        Debug.LogWarning("Drag a valid story JSON file into the StoryReader component.");
        enabled = false;
    }

    //delete saved story
     if (deleteStorySaved)
    {

        PlayerPrefs.DeleteKey("inkSaveState");

    }

    //load saved story
    if (PlayerPrefs.HasKey("inkSaveState") == true)
    {
        string storyJonsSaved = PlayerPrefs.GetString("inkSaveState");
        //Debug.Log("--"+storyJons+"---");
        story.state.LoadJson(storyJonsSaved);
    }else
    {
        story = new Story(storyJSON.text);

    }

    //story = new Story(storyJons);
    StartCoroutine(OnAdvanceStory());
    //PlayerPrefs.SetString("ciao", "prova");
}

public void Clear () {
    StopAllCoroutines();
    ClearContent();
    choiceContainerView.Clear();
    contentManager.enabled = false;
    settingsButton.Hide();
    settingsView.Hide();
}

private void ClearContent () {
    for (int i = contentParent.childCount-1; i >= 0; i--) {
        Destroy(contentParent.GetChild(i).gameObject);
    }
}

IEnumerator OnAdvanceStory () {

    if (story.canContinue) {
        ChoiceGroupView choiceView = null;
        ChevronButtonView chevronView = null;
        int cont = 0;
        while (story.canContinue) {

            cont++;
            string content = story.Continue().Trim();
            if (content == "") 
            {
                content = "\n";
            }

            ContentView contentView = CreateContentView(content);
            Debug.Log("conta " + cont);

            if (cont >= 2) //save strory
            {
                string savedState = story.state.ToJson();
                PlayerPrefs.SetString("inkSaveState", savedState);
                changeAudio(0);
            }

            if (!story.canContinue) {
                if(story.currentChoices.Count > 0) {
                    choiceView = CreateChoiceGroupView(story.currentChoices);
                } else {
                    chevronView = CreateChevronView();
                }
            }
            while(contentView.textTyper.typing)
                yield return null;

            if(story.canContinue)
                yield return new WaitForSeconds(Mathf.Min(1.0f, contentView.textTyper.targetText.Length * 0.01f));
        }
        if(story.currentChoices.Count > 0) {
            yield return new WaitForSeconds(1f);
            choiceView.RenderChoices();
            yield return new WaitForSeconds(0.5f);
        } else {
            chevronView.Render();
            yield return new WaitForSeconds(2);
        }
    } else {
        yield return new WaitForSeconds(2);
        CreateChevronView();
    }
}

public void ChooseChoiceIndex (int choiceIndex) {

    DestroyEmpties();
    story.ChooseChoiceIndex(choiceIndex);
    hasMadeAChoice = true;
    StartCoroutine(OnAdvanceStory());
}

private void DestroyEmpties () {
    EmptyView[] emptyViews = contentParent.GetComponentsInChildren<EmptyView>();
    for (int i = emptyViews.Length-1; i >= 0; i--) {
        Destroy(emptyViews[i].gameObject);
    }
}

public void ClickChevronButton () {
    Complete();
}

ContentView CreateContentView (string content) {
    ContentView contentView = Instantiate(contentViewPrefab);
    contentView.transform.SetParent(contentParent, false);
    contentView.LayoutText(content);
    return contentView;
}

// Creates a textbox showing the the line of text
/*
void CreateContentView2(string text)
{
    Text storyText = Instantiate(textPrefab) as Text;
    storyText.text = text;
    storyText.transform.SetParent(canvas.transform, false);
}
*/

ChoiceGroupView CreateChoiceGroupView (IList<Choice> choices) {
    ChoiceGroupView choiceGroupView = Instantiate(choiceGroupViewPrefab);
    choiceGroupView.transform.SetParent(choiceContainerView.transform, false);
    choiceGroupView.LayoutChoices(choices);
    CreateEmptyView(choiceGroupView.rectTransform.sizeDelta.y);
    return choiceGroupView;
}

ChevronButtonView CreateChevronView () {
    ChevronButtonView chevronView = Instantiate(chevronViewPrefab);
    chevronView.transform.SetParent(choiceContainerView.transform, false);
    CreateEmptyView(chevronView.rectTransform.sizeDelta.y);
    return chevronView;
}

EmptyView CreateEmptyView (float height) {
    EmptyView emptyView = Instantiate(emptyViewPrefab);
    emptyView.transform.SetParent(contentParent, false);
    emptyView.layoutElement.preferredHeight = height;
    return emptyView;
}
/*
void  setAudio()
{
    backGroundAudio.audioSource.clip = backGroundAudio.audioClips[0];
    backGroundAudio.NormalMode();
    //subroutine
}
*/

void changeBackground()
{
    Debug.Log("sono backgrodu");
    Image images = contentManager.GetComponentInChildren<Image>();
    images.sprite = Sprite.Create(contentManager.imagesBackGround[0], new Rect(0.0f, 0.0f, contentManager.imagesBackGround[0].width, contentManager.imagesBackGround[0].height), new Vector2(0.5f, 0.5f), 100.0f);

    //get background

    /*
    Image[] images = PlayerBarExample.GetComponentsInChildren<Image>();
    Image face = images[0];
    foreach (Image image in images)
    {
        if (image.gameObject.CompareTag("face"))
            face = image;
    }
}
*/
}

void changeAudio(int audioClip)
{
    Main.Instance.backgroundAmbienceController.QuietMode();
    Main.Instance.backgroundAmbienceController.changeAudioClip(audioClip);
    Main.Instance.backgroundAmbienceController.HightMode();
    /* vecchio  modo
    Debug.Log("sto cambiando il sound");
    Main.Instance.backgroundAmbienceController.audioSource.volume = 0;
    IEnumerator fadeSound1 = Main.Instance.backgroundAmbienceController.fadeOut(Main.Instance.backgroundAmbienceController.audioSource, 0.3f);
    StartCoroutine(fadeSound1);
    Main.Instance.backgroundAmbienceController.changeAudioClip();
    IEnumerator fadeSound2 = Main.Instance.backgroundAmbienceController.fadeIn(Main.Instance.backgroundAmbienceController.audioSource, 2.5f);
    StartCoroutine(fadeSound2);
    */

}

public string getStoryLoaded()
{
    string storySaved = "";
    if (PlayerPrefs.HasKey("inkSaveState") == true)
    {
        storySaved = PlayerPrefs.GetString("inkSaveState");
        //inkStory.state.LoadJson(savedState);
    }
    Debug.Log("sono la storia: " + storySaved);
    return storySaved;
}

public void saveStory()
{
    Debug.Log("save story game state");
    string savedState = story.state.ToJson();

    PlayerPrefs.SetString("inkSaveState", savedState);
}

/*
 * PlayerPrefs.DeleteKey("inkSaveState");

_inkStory.ResetState()C */

/*
private saveStory()
{
    var savedState = _inkStory.state.ToJson();
    PlayerPrefs.SetString("inkSaveState", savedState);
}
*/

}

javasilk commented 4 years ago

this is the json that I saved { "choiceThreads": { "5": { "callstack": [{ "cPath": "vasca.0", "idx": 9, "exp": false, "type": 0 }], "threadIndex": 5, "previousContentObject": "vasca.0.8" } }, "callstackThreads": { "threads": [{ "callstack": [{ "exp": false, "type": 0 }], "threadIndex": 3, "previousContentObject": "vasca.0.9" }], "threadCounter": 5 }, "variablesState": {}, "evalStack": [], "outputStream": ["^Lentamente ma inesorabilmente lo spingo in avanti, e lo tengo sotto finché non smette di agitarsi.", "\n"], "currentChoices": [{ "text": "Ansimando...", "index": 0, "originalChoicePath": "vasca.0.9", "originalThreadIndex": 5, "targetPath": "vasca.0.c-0" }], "visitCounts": { "crediti1": 1, "intro": 1, "intro.0.c-0": 1, "prologo": 1, "prologo.0.c-0": 1, "28gennaio": 1, "28gennaio.0.c-0": 1, "vasca": 1 }, "turnIndices": {}, "turnIdx": 2, "storySeed": 19, "previousRandom": 0, "inkSaveVersion": 8, "inkFormatVersion": 19 }