Home > database >  Why getting error Coroutine couldn't be started because the the game object 'SaveInOtFade
Why getting error Coroutine couldn't be started because the the game object 'SaveInOtFade

Time:07-27

I checked few times and the object prefab 'SaveInOtFade Canvas' is not inactive it's a prefab. i tried to drag the prefab to the hierarchy and the object is not disabled and still getting the error :

Coroutine couldn't be started because the the game object 'SaveInOtFade Canvas' is inactive!

The line :

StartCoroutine(CanvasAlphaChangeOverTime(canvas, fadingSpeed));

The script :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FadeInOutSaveGameText : MonoBehaviour
{
    public Canvas canvas;
    public float fadingSpeed;

    private bool stopFading = false;
    private const float THRESHOLD = 0.01F;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    IEnumerator CanvasAlphaChangeOverTime(Canvas canvas, float duration)
    {
        float alphaColor = canvas.GetComponent<CanvasGroup>().alpha;

        while (true)
        {
            alphaColor = (Mathf.Sin(Time.time * duration)   1.0f) / 2.0f;
            canvas.GetComponent<CanvasGroup>().alpha = alphaColor;

            // only break, if current alpha value is close to 0 or 1
            if (stopFading && Mathf.Abs(alphaColor) <= THRESHOLD)//if (stopFading && (Mathf.Abs(alphaColor) <= THRESHOLD || Mathf.Abs(alphaColor - 1) <= THRESHOLD))
            {
                break;
            }

            yield return null;
        }
    }

    public IEnumerator OverAllTime(float time)
    {
        stopFading = false;

        StartCoroutine(CanvasAlphaChangeOverTime(canvas, fadingSpeed));

        yield return new WaitForSeconds(time);

        stopFading = true;
    }
}

And this line :

StartCoroutine(fadeInOutSaveGame.OverAllTime(savingFadeInOutTime));

In this script :

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class SaveLoad : MonoBehaviour
{
    public FadeInOutSaveGameText fadeInOutSaveGame;
    public float timeToStartSaving;
    public float savingFadeInOutTime;

    private List<GameObject> objectsToSave;
    private string saveString;

    private void Awake()
    {
        Init();

        Debug.Log("Start");

        for (int i = 0; i < objectsToSave.Count; i  )
        {
            Debug.Log($"{i}");
            Debug.Log($"{objectsToSave[i].name}");
        }

        Debug.Log("End Init");
    }

    public void Save(string FolderToSave, string FileName)
    {
        SaveGame saveGame = new SaveGame();
        saveGame.saveObjects = new List<SaveObject>();
        for (int i = 0; i < objectsToSave.Count; i  )
        {
            SaveObject saveObject = new SaveObject();
            saveObject.transformSaver = new TransformSaver();
            
            Debug.Log($"{i}");
            Debug.Log($"{objectsToSave[i].name}");
            saveObject.gameObjectUniqueID = objectsToSave[i].GetComponent<GenerateGuid>().uniqueGuidID;
            var x = objectsToSave[i].GetComponents<Component>();
            var stateQueryComponent = x.Where(component => component is IStateQuery).ToList();
            List<KeyToValue> componentsState = new List<KeyToValue>();
            foreach (var z in stateQueryComponent)
            {
                var w = z as IStateQuery;
                componentsState.Add(new KeyToValue(w.UniqueId.ToString(), w.GetState()));
            }

            saveObject.transformSaver.position = objectsToSave[i].transform.position;
            saveObject.transformSaver.rotation = objectsToSave[i].transform.rotation;
            saveObject.transformSaver.scaling = objectsToSave[i].transform.localScale;

            saveObject.componentsState = componentsState;
            saveGame.saveObjects.Add(saveObject);
        }

        string json = JsonUtility.ToJson(saveGame);

        if (FolderToSave == null && FileName == null)
        {
            SaveSystem.Save(json);
        }
        else
        {
            SaveSystem.Save(json, FolderToSave, FileName);
        }
    }

    public void Load(string FolderToSave, string FileName)
    {
        Dictionary<string, GameObject> uniqueIdToObject = objectsToSave
            .ToDictionary(o => o.GetComponent<GenerateGuid>().uniqueGuidID, o => o);
        if (FolderToSave == null && FileName == null)
        {
            saveString = SaveSystem.Load();
        }
        else
        {
            saveString = SaveSystem.Load(FolderToSave, FileName);
        }

        if (saveString != null)
        {
            SaveGame saveGame = JsonUtility.FromJson<SaveGame>(saveString);
            foreach (var saveObject in saveGame.saveObjects)
            {
                List<KeyToValue> loadedComponents = saveObject.componentsState;
                var objectToSetState = uniqueIdToObject[saveObject.gameObjectUniqueID];

                objectToSetState.transform.position = saveObject.transformSaver.position;
                objectToSetState.transform.rotation = saveObject.transformSaver.rotation;
                objectToSetState.transform.localScale = saveObject.transformSaver.scaling;

                var y = objectToSetState.GetComponents<Component>();
                var z = y.Where(component => component is IStateQuery).ToList();
                Dictionary<string, IStateQuery> zz = z.ToDictionary(sq => (sq as IStateQuery).UniqueId.ToString(), sq => sq as IStateQuery);

                foreach (KeyToValue keyvalue in loadedComponents)
                {
                    zz[keyvalue.Key].SetState(keyvalue.Value);
                }
            }
        }
    }

    public IEnumerator SaveWithTime()
    {
        yield return new WaitForSeconds(timeToStartSaving);

        Save(null,null);

        StartCoroutine(fadeInOutSaveGame.OverAllTime(savingFadeInOutTime));
    }

    public IEnumerator SaveWithTime(string FolderToSave, string FileName)
    {
        yield return new WaitForSeconds(timeToStartSaving);

        Save(FolderToSave, FileName);

        StartCoroutine(fadeInOutSaveGame.OverAllTime(savingFadeInOutTime));
    }

    public void Init()
    {
        SaveSystem.Init();

        if (objectsToSave == null)
        {
            objectsToSave = new List<GameObject>();
        }

        var objectsWithGenerateGuid = GameObject.FindObjectsOfType<GenerateGuid>().ToList();
        if (objectsWithGenerateGuid.Count > 0 && objectsToSave.Count == 0)
        {
            for (int i = 0; i < objectsWithGenerateGuid.Count; i  )
            {
                objectsToSave.Add(objectsWithGenerateGuid[i].gameObject);
            }
        }
    }
}

The scene screenshots :

Scene settings

And the script Saving Game :

using UnityEngine;
using System.Collections;
using System.IO;

public class SavingGame : MonoBehaviour
{
    public int resWidth = 1920;
    public int resHeight = 1080;
    public SaveLoad saveLoad;

    public static string ScreenShotName(int width, int height)
    {
        return string.Format("{0}/Saved Screenshots/SavedGameSlot_{1}x{2}_{3}.png",
                             Application.dataPath,
                             width, height,
                             System.DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss"));
    }

    void Update()
    {
        if (Input.GetKeyDown("k"))
        {
            string filename = ScreenShotName(resWidth, resHeight);
            string directory = Path.GetDirectoryName(filename);
            Directory.CreateDirectory(directory);
            ScreenCapture.CaptureScreenshot(filename);
            StartCoroutine(saveLoad.SaveWithTime(directory,Path.GetFileNameWithoutExtension(filename)   ".savegame.txt"));
        }
    }
}

When i'm pressing the k key to save the game i'm getting the error.

CodePudding user response:

You cannot start a coroutine function from a script that has its GameObject de-activated.

The StartCoroutine function is a function under the MonoBehaviour class. When you have to start a coroutine on a deactivated GameObject, you need a reference to a MonoBehaviour object that has an active GameObject.

this url will help you. Start coroutine on an inactive/de-activated GameObject

  • Related