SchultzGames
Para tirar dúvidas, crie um tópico especifico na área "Dúvidas em Geral" e aguarde ser respondido. Evite comentar em tópicos não relacionados a sua dúvida :D
TÓPICOS RECENTES:
Tópico:
Postado em:
Postado por:
ShapeKeys do Blender para a Unity altera áreas próximas
COMO EVITAR QUE UM OBJETO (PLAYER,ITEM ETC...) ATRAVESSE UMA PAREDE.
Ajuda em Script de Verificação de Ação e Reação
unity Failed to load PlayerSettings (internal index #0). Most likely data f
modelar avatar e skins para um jogo web
PRECISO FAZER QUE MEU GAME FIQUE ONLINE
Materiais do Blander não aparecem no MeshRendere do Objeto na Unity
Repetiçoes de Textura no Terreno
SERVER IS DOWN - UNITY+MSQL
Procuro programadores - Novo jogo
Problema com o MS VEHICLES
Preciso de ajuda com a Unity
Problema com vídeo em 360° na Unity
Problemas no MS Vehicles
unity- eventos na Animação com Armature/Bones vinda do blender não funciona
ajuda exibir resultados simulados em uma liga Game Unity
Unity - ParticleSystem não é redirecionado no rawimage no canvas
Como resolver o problema de "face orientation" no Blender.
[DÚVIDA] Tive um problema com meu Canvas
erro na Directional Light
Problemas com o Directional Light da Unity 3D
210 Linhas de código para inimigo é muito grande?
Novo jogo da franquia Sphere game em desenvolvimento
malha da roda não girando com wheel collider unity
Problemas com ambiguidade
Touch mobile
INVALID TOKEN
Como acessar o "HD Render Pipeline" do HDRP por script?
CHAT GPT PRA JOGO DE TIRO? comentem
Tutorial script inimigo segue e foge do player
Ainda vale a pena lançar Asset na Asset Store?
Ajuda com tabela de historico de pontuaçao.
[TUTORIAL] Entrar no carro estilo GTA
Como derrapar um Whell Collider
Como altertar o valor do "Asymptote Value" do Whell Collider via Script
Preciso de ajuda para substituir valor de variavel em outro script
Ajuda com Top Down Shooter utilizando Photon
Duvida com Netcode
[RESOLVIDO] Unity - Movendo a Câmera na Horizontal/Vertical com Touch
Alguém me ajuda com os anúncios pfv
Segundo Trailer do jogo Dark Age, Feliz Natal a todos!
Unity - ScrollRect, Viewport, Content - O Conteúdo ñ inicia no topo
Coleta de itens
Unity - Cadastro do email do jogador
[GRATIS] PACK DE MODELOS 3D PARA JOGO DE TERROR
Onde Conseguir músicas para meu Jogo?
error CS0246 em Script
Alguem teve ja esse problema?
[Projeto em Andamento] Draug, um jogo de hordas
DISPONIVEL PARA FAZER MODELOS 3D
Unity-Loja.Como os Jogadores terão acesso aos ítens comprados na PlayStore?
Bugando depois do Build.
Primeiro Trailer do jogo Dark Age
Problema com sombra
Mesh e Material do objeto trocando para uma instancia no inicio do jogo
[RESOLVIDO] Unity - RawImages_Layer_Camera
INVESTIMENTO EM JOGOS E BANCO DE TALENTO
Teaser do meu novo projeto pessoal, Dark Age
Preciso de ajuda com mudança para mobile androide.
[RESOLVIDO] Posição final do objeto em jogo 2D
Input.GetAxis() obedercer a orientação de um objeto.
Interação com elementos UI
Meu primeiro jogo na steam
Minimap/Radar/GPS Estilo GTA V
[RESOLVIDO] Erro no console depois que formatei o pc
PACK GRÁTIS de Músicas ELETRÔNICAS para ajudar vocês em seus Jogos Indies!
[TUTORIAL] Entenda como funciona: ENUM, SWITCH, BREAK, CASE no C#
O Labirinto II - Baixe o Jogo
Qual e o codigo de Botões na unity para saber seus estados?
Como carregar itens pequenos dentro do carro sem que atravesse os colliders
[Duvida] Script pegar itens
Travamento ao trocar de cena
Colisão zoada e movimentação
Salvar objetos que foram destruidos entre cenas na unity
Quero começa a desenvolver um jogo de luta porem eu queria aprender a faze
Pegar qual objeto colidiu com o Linecast.
movimentação e camera?
[RESOLVIDO] Unity - SceneManager.LoadScene abre scene com objeto "vazio"
[RESOLVIDO] ajuda sobre skybox
MEU SIMULADOR DE CARRO
[_____IMPORTANTE_____] ALTERAÇÕES NA POLÍTICA DE COBRANÇA DA UNITY
[RESOLVIDO] Ausencia da funçao NavMesh na Unity 2022.2.12
[_____IMPORTANTE_____] ALTERAÇÕES NA POLÍTICA DE COBRANÇA DA UNITY - 2
Roll Up Um jogo de aventura e desáfios
Terminologia da Unity em outras engines
Como criar a iluminação do Sol no Sistema Solar?
Conexão de lobby pelo OnConnectedToMaster
Problema na exportção de projeto unity
[RESOLVIDO] Unity - Áudios estão emitindo som só Depois do Botão ser solto
Unity - Banco de Dados Online junto ao Jogo
Player virar para o inimigo(Prefab)
[TUTORIAL] Sistema De Save Game Ao Sair Da Fase
Problema de Sincronização de um objeto de um jogo multiplayer usa q Photon
Unity - Compartilhar meu Jogo
Alguém que manja do Google ADmob?
Unity - Avaliar meu Jogo
[RESOLVIDO] Destruir inimigo com o player.
Salvar e carregar dados na Unity de objetos prefabs sem sobrescrever os dad
Unity - Salvar os Dados do Jogador Online
Ontem à(s) 10:09 pm
Dom Mar 10, 2024 2:30 pm
Sex Mar 01, 2024 1:27 pm
Qui Fev 22, 2024 9:57 pm
Qua Fev 21, 2024 10:39 am
Ter Fev 20, 2024 9:28 am
Ter Fev 20, 2024 12:15 am
Seg Fev 19, 2024 1:06 pm
Seg Fev 12, 2024 1:56 pm
Seg Fev 12, 2024 1:17 pm
Dom Fev 11, 2024 8:55 pm
Dom Fev 11, 2024 11:16 am
Seg Fev 05, 2024 4:18 pm
Dom Fev 04, 2024 9:39 pm
Qua Jan 31, 2024 11:59 pm
Ter Jan 30, 2024 7:37 pm
Ter Jan 23, 2024 6:33 pm
Dom Jan 21, 2024 6:03 pm
Sáb Jan 20, 2024 7:03 pm
Sáb Jan 20, 2024 6:58 pm
Sáb Jan 20, 2024 6:39 pm
Sex Jan 19, 2024 1:29 pm
Sex Jan 19, 2024 8:40 am
Dom Jan 14, 2024 5:30 pm
Qua Jan 10, 2024 10:29 pm
Qua Jan 10, 2024 8:55 pm
Qua Jan 10, 2024 7:14 pm
Ter Jan 09, 2024 3:55 pm
Ter Jan 09, 2024 8:04 am
Sáb Jan 06, 2024 8:02 pm
Sex Jan 05, 2024 7:01 am
Sex Jan 05, 2024 12:12 am
Qui Jan 04, 2024 6:55 pm
Qui Jan 04, 2024 12:52 pm
Qui Jan 04, 2024 4:34 am
Ter Jan 02, 2024 11:48 pm
Dom Dez 31, 2023 7:25 pm
Qua Dez 27, 2023 5:44 pm
Qua Dez 27, 2023 3:08 pm
Sáb Dez 23, 2023 7:27 pm
Sáb Dez 23, 2023 5:06 pm
Qui Dez 21, 2023 8:10 pm
Seg Dez 18, 2023 2:04 pm
Sex Dez 15, 2023 5:11 pm
Qui Dez 14, 2023 9:13 pm
Qui Dez 14, 2023 2:47 pm
Qui Dez 14, 2023 1:48 pm
Qua Dez 13, 2023 8:58 pm
Ter Dez 12, 2023 2:32 pm
Seg Dez 11, 2023 1:53 pm
Qua Dez 06, 2023 8:13 pm
Sáb Dez 02, 2023 8:06 pm
Qui Nov 30, 2023 7:49 am
Seg Nov 27, 2023 1:35 am
Qua Nov 22, 2023 7:37 am
Qui Nov 09, 2023 1:22 pm
Seg Nov 06, 2023 11:59 am
Ter Out 31, 2023 9:53 am
Dom Out 29, 2023 8:05 pm
Dom Out 29, 2023 3:03 am
Sex Out 27, 2023 3:43 pm
Sex Out 27, 2023 3:28 pm
Qua Out 25, 2023 1:20 pm
Seg Out 23, 2023 10:34 am
Dom Out 22, 2023 6:55 pm
Qui Out 19, 2023 11:57 pm
Qui Out 19, 2023 6:39 pm
Ter Out 17, 2023 6:37 pm
Ter Out 17, 2023 6:18 pm
Seg Out 16, 2023 1:59 pm
Sáb Out 14, 2023 12:15 pm
Qua Out 11, 2023 6:07 pm
Seg Out 09, 2023 4:19 pm
Qua Out 04, 2023 12:12 pm
Qua Out 04, 2023 12:11 pm
Ter Out 03, 2023 9:18 pm
Ter Out 03, 2023 9:08 pm
Ter Out 03, 2023 6:05 pm
Ter Set 26, 2023 12:45 pm
Seg Set 25, 2023 9:02 pm
Seg Set 25, 2023 9:47 am
Sáb Set 23, 2023 2:10 pm
Sex Set 22, 2023 9:01 pm
Qui Set 21, 2023 11:04 am
Qua Set 20, 2023 4:40 pm
Qua Set 20, 2023 9:15 am
Dom Set 17, 2023 12:17 pm
Sex Set 15, 2023 7:24 pm
Sex Set 15, 2023 5:41 pm
Sex Set 15, 2023 4:28 pm
Sex Set 15, 2023 10:56 am
Sex Set 15, 2023 10:15 am
Seg Set 11, 2023 11:43 am
Seg Set 11, 2023 11:31 am
Sáb Set 09, 2023 4:53 pm
Sáb Set 09, 2023 1:44 pm
Ter Set 05, 2023 11:12 pm
Ter Set 05, 2023 3:12 pm
Seg Set 04, 2023 11:53 pm



































































































Salvar dados

3 participantes

Ir para baixo

DÚVIDA Salvar dados

Mensagem por arnaldojunior Qua maio 02, 2018 2:30 pm

Olá estou tentando criar um sistema para salvar os dados da cena, vi alguns tutoriais sobre salvar em binário e que para tanto não posso referenciar nada do meu arquivo de gerenciamento como publico. mas encontrei problemas logo de cara para salvar as barras de estamina e vida.
Ambas usam slider para definir seu valor.


Código:



using System.Collections;

using UnityEngine.UI;

using System.Collections.Generic;

using UnityEngine;

using System;

public class UIManager : MonoBehaviour {



    public static UIManager instance;



    public Slider barrastamina, BarraDeVida;

    public float perda, ganho;

    public int QuantSede=0;

    private bool Sede=false;







    // Use this for initialization

    void Awake ()

    {



    }



    // Update is called once per frame

    void Update ()

    {

        //===========================================Controle da Stamina===========================================//

        if (Time.timeScale > 0)

        {

            if (Input.GetKey(KeyCode.LeftShift))

            {

                if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D))

                {

                    barrastamina.value -= perda;

                    QuantSede++;

                }

            }



            if (Input.GetKey(KeyCode.Space))

            {

                barrastamina.value -= perda / 2;

                QuantSede++;

            }



            if (Input.GetKey(KeyCode.Mouse0))

            {

                barrastamina.value -= perda / 2;

                QuantSede++;

            }



            if (Sede == false)

            {

                if (barrastamina.value > 2)

                {

                    if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D))

                    {

                        barrastamina.value += ganho / 3;

                    }

                    else

                    {

                        barrastamina.value += ganho;

                    }

                }

                else

                {

                    if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D))

                    {

                        barrastamina.value += ganho / 20;

                    }

                    else

                    {

                        barrastamina.value += ganho;

                    }

                }

            }

            if (QuantSede >= 15000)

            {

                Sede = true;

            }

            else

            {

                Sede = false;

            }



        }



    }



}



Como podem ver só implementei a estamina por enquanto.
Mas ai vem o problema, não sei como pegar esse dado da barra estamina e envia-lo ao script de game manager e depois busca-lo novamente quando o save for recarregado.
Código:



using System.Collections;

using System.Collections.Generic;

using UnityEngine;



public class GameManager : MonoBehaviour {



    public static GameManager instance;



    // Use this for initialization

    void Awake()

    {

        if (instance == null)

        {

            instance = this;

            DontDestroyOnLoad(gameObject);

        }

        else if (instance != null)

        {

            Destroy(gameObject);

        }

    }



    // Update is called once per frame



    void Update ()

    {



    }



}

Ainda não implementei nada neste script, mas só para terem uma ideia do que se trata. Pensei em criar uma void no UImanager que enviasse o valor para o Game manager, mas como defino o valor do slider barrastamina?
Agradeço se puderem me ajudar neste problema.

arnaldojunior
Membro
Membro

PONTOS : 2804
REPUTAÇÃO : 2
Respeito as regras : Salvar dados WvDYdlf

Ir para o topo Ir para baixo

DÚVIDA Re: Salvar dados

Mensagem por Callyde Jr Sex maio 04, 2018 12:14 pm

Voce vai ter que fazer no script as variaveis int ou float
E salvalas no outro script.
EX:
Código:
using System.Collections;

using UnityEngine.UI;

using System.Collections.Generic;

using UnityEngine;

using System;

public class UIManager : MonoBehaviour {



    public static UIManager instance;
    public float stamina = 100;
    public float Vida = 100;



    public Slider barrastamina, BarraDeVida;

    public float perda, ganho;

    public int QuantSede=0;

    private bool Sede=false;







    // Use this for initialization

    void Awake ()

    {



    }



    // Update is called once per frame

    void Update ()

    {
   barrastamina.value = stamina;
    BarraDeVida.value = Vida;
        //===========================================Controle da Stamina===========================================//

        if (Time.timeScale > 0)

        {

            if (Input.GetKey(KeyCode.LeftShift))

            {

                if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D))

                {

                    barrastamina.value -= perda;

                    QuantSede++;

                }

            }



            if (Input.GetKey(KeyCode.Space))

            {

                barrastamina.value -= perda / 2;

                QuantSede++;

            }



            if (Input.GetKey(KeyCode.Mouse0))

            {

                barrastamina.value -= perda / 2;

                QuantSede++;

            }



            if (Sede == false)

            {

                if (barrastamina.value > 2)

                {

                    if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D))

                    {

                        barrastamina.value += ganho / 3;

                    }

                    else

                    {

                        barrastamina.value += ganho;

                    }

                }

                else

                {

                    if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D))

                    {

                        barrastamina.value += ganho / 20;

                    }

                    else

                    {

                        barrastamina.value += ganho;

                    }

                }

            }

            if (QuantSede >= 15000)

            {

                Sede = true;

            }

            else

            {

                Sede = false;

            }



        }



    }



}

Callyde Jr
Callyde Jr
Programador

Masculino PONTOS : 4919
REPUTAÇÃO : 444
Idade : 45
Áreas de atuação : Iniciante em modelagem Blender,Sketchup
Programador
Idealista

Meu Canal
https://www.youtube.com/ch
Respeito as regras : Salvar dados WvDYdlf

http://unnygames.000webhostapp.com/

Ir para o topo Ir para baixo

DÚVIDA Re: Salvar dados

Mensagem por arnaldojunior Dom maio 06, 2018 8:54 pm

Não sei o que fiz mas minha resposta não apareceu, se aparecer para vocês desculpem a duplicidade.

Consegui salvar os dados, tive problemas pelo teste da "cena", mas criei uma outra variável e armazenei os dados quando estava pausado, então só tive de fazer um teste para me certificar que não estava salvando o main menu. Pensando agora acho que vou testar a cena pelo nome dela, se for "main menu" salvo a anterior.
Código:



using System.Collections;

using System.Collections.Generic;

using UnityEngine.UI;

using UnityEngine;

using System.Runtime.Serialization.Formatters.Binary;

using System.IO;

using System;

using UnityEngine.SceneManagement;



public class GameManager : MonoBehaviour {



    public static GameManager instance;

    private SaveGameData savedGame;

    private float barraStaminaDados;

    private const string File_Path = "saveGameData.dat";

    private bool isNewGame=false;

    private Vector3 positionPlayerDados;

    private int stageAnte,stageAtual;





    // Use this for initialization 

    void Awake()

    {

        if (instance == null)

        {

            instance = this;

            DontDestroyOnLoad(gameObject);

        }

        else if (instance != null)

        {

            Destroy(gameObject);

        }

    }

    private void Start()

    {

        Load();

    }



    private void Update()

    {

        if(Time.timeScale==0)

        {

            stageAnte = SceneManager.GetActiveScene().buildIndex;

        }

    }



    void OnEnable()

    {

        PLAYER.PlayerPosicao += OnPlayerPosicao;

        UIManager.StaminaControl += OnStaminaControl;

        SceneManager.sceneLoaded += OnStageLoad;

    }



    private void OnDisable()

    {

        PLAYER.PlayerPosicao -= OnPlayerPosicao;

        UIManager.StaminaControl -= OnStaminaControl;

        SceneManager.sceneLoaded -= OnStageLoad;

    }



    void OnPlayerPosicao()

    {

        positionPlayerDados = PLAYER.positionPlayer;

    }



    void OnStaminaControl()

    {

        barraStaminaDados = UIManager.valBarraStamina;        

    }



    void OnStageLoad(Scene scene, LoadSceneMode mode)

    {

        if (!isNewGame && savedGame!=null)

        {

            barraStaminaDados = savedGame.barraStaminaSave;

            UIManager.valBarraStamina = barraStaminaDados;



            PLAYER.instance.transform.position = new Vector3(savedGame.spositionX, savedGame.spositionY, savedGame.spositionZ);



            isNewGame = true;



            UIManager.instance.UpdateUI();

        }

    }



    void SceneControl()

    {

        stageAtual= SceneManager.GetActiveScene().buildIndex;

        if (stageAtual != stageAnte)

        {

            stageAtual = stageAnte;

        }

    }



    public void SaveGame()

    {

        BinaryFormatter bf = new BinaryFormatter();

        FileStream file = File.Create(Path.Combine(Application.streamingAssetsPath, File_Path));



        SaveGameData save = new SaveGameData();

        save.barraStaminaSave = barraStaminaDados;



        save.spositionX = positionPlayerDados.x;

        save.spositionY = positionPlayerDados.y;

        save.spositionZ = positionPlayerDados.z;

        save.stage = stageAtual;



        bf.Serialize(file, save);



        file.Close();

    }



    public void Load()

    {

        if (File.Exists(Path.Combine(Application.streamingAssetsPath, File_Path)))

        {

            BinaryFormatter bf = new BinaryFormatter();

            FileStream file = File.Open(Path.Combine(Application.streamingAssetsPath, File_Path), FileMode.Open);



            SaveGameData save = (SaveGameData) bf.Deserialize(file);



            savedGame = save;



            file.Close();

        }



    }



    private void OnApplicationQuit()

    {

        SceneControl();

        SaveGame();

    }



    public void NewGame()

    {

        isNewGame = true;

        LoadStage(1);

    }



    public void LoadGame()

    {

        isNewGame = false;

        Load();

        LoadStage(savedGame.stage);



    }



    public void LoadStage(int stage)

    {

        SceneManager.LoadScene(stage);

    }



}





[Serializable]

class SaveGameData

{

    public float barraStaminaSave;



    public float spositionX;

    public float spositionY;

    public float spositionZ;



    public int stage;

}



Agora estou com uma duvida. Carreguei o jogo e tudo funcionou, mas se volto ao menu principal e tento carregar o jogo novamente, não consigo. Também percebi que quando entro no jogo pela primeira vez e clico em new game ele carrega o save, sendo necessário voltar ao "main menu" e clicar novamente em new game.

arnaldojunior
Membro
Membro

PONTOS : 2804
REPUTAÇÃO : 2
Respeito as regras : Salvar dados WvDYdlf

Ir para o topo Ir para baixo

DÚVIDA Re: Salvar dados

Mensagem por Callyde Jr Dom maio 06, 2018 10:52 pm

Tenta fazer um script para Salvar em cada scene e o de Load no menu
Callyde Jr
Callyde Jr
Programador

Masculino PONTOS : 4919
REPUTAÇÃO : 444
Idade : 45
Áreas de atuação : Iniciante em modelagem Blender,Sketchup
Programador
Idealista

Meu Canal
https://www.youtube.com/ch
Respeito as regras : Salvar dados WvDYdlf

http://unnygames.000webhostapp.com/

Ir para o topo Ir para baixo

DÚVIDA Re: Salvar dados

Mensagem por arnaldojunior Seg maio 07, 2018 12:52 am

Você diz acrescentar um evento para carregar o jogo no menu de pausa, além do menu principal?
Posso até tentar, mas acho que meu problema é que ele só salva quando fecho e como o arquivo deserealiza quando carrego ele não aceita carregar novamente.
eu poderia fazer como você diz, mas serializar o save na transição e cena. Isso não daria problemas se a cena alterasse mais de uma vez?

arnaldojunior
Membro
Membro

PONTOS : 2804
REPUTAÇÃO : 2
Respeito as regras : Salvar dados WvDYdlf

Ir para o topo Ir para baixo

DÚVIDA Re: Salvar dados

Mensagem por brunocvz Seg maio 14, 2018 7:19 pm

vc poderia fazer isso por PlayerPrefab, salvar em binario ou salvar em um banco de dados como o do firebase.
pensando em colocar o jogo no mercado acho que vc poderia pensar em usar o firebase por que ele já tem exemplos para vc fazer um esquema de login, importa e exporta dados,salvar pontuação e depois puxar do banco de dados entre outra coisas como analytics

brunocvz
Iniciante
Iniciante

PONTOS : 2766
REPUTAÇÃO : 7
Respeito as regras : Salvar dados WvDYdlf

Ir para o topo Ir para baixo

DÚVIDA Re: Salvar dados

Mensagem por arnaldojunior Seg maio 14, 2018 11:05 pm

Eu consigo salvar, e percebi que o meu problema era na booleana de novo jogo, mas estou tendo um novo problema. o script base para salvar em binário vi em tutorial, mas acrescentei algumas funções a mais para testar cenas e guardar variáveis temporárias. Agora quando quero iniciar um novo jogo ele carrega todos os dados do save.
Código:



using System.Collections;

using System.Collections.Generic;

using UnityEngine;



public class PLAYER : MonoBehaviour {



    public static PLAYER instance;



    public delegate void PlayerDados();

    public static event PlayerDados PlayerPosicao;

    public static event PlayerDados PlayerLevel;

    public static event PlayerDados PlayerXP;



    public static float vidaPlayer = 100;

    public static int playerLVLDados =1, xpPlayerDados=0;

    public static Vector3 positionPlayer;

    private int playerLVL =1, xpPlayer = 0;    

    private int xpDoInimigo;

    public int Teste_xp_que_vira_do_inimigo;



    //--------------------------Use this Before Inicialization-----------------------------------//

    private void Awake()

    {

        if (instance == null)

        {

            instance = this;

        }

        else if (instance != null)

        {

            Destroy(gameObject);

        }

        PlayerLevel();

        PlayerXP();

    }



    public void PosicaoInicial()

    {        

        Debug.Log("Posição Inicial " + this.transform.position);

    }



    public void DadosAtual()

    {

        playerLVL = playerLVLDados;

        xpPlayer = xpPlayerDados;



    }



    void Experience()

    {

        xpDoInimigo = Teste_xp_que_vira_do_inimigo;

        xpPlayer = xpPlayer + xpDoInimigo;

        xpPlayerDados = xpPlayer;

        xpDoInimigo = 0;



        PlayerXP();



        if (xpPlayer >= (100f * playerLVL*(playerLVL+(playerLVL-1))))

        {

            playerLVL++;

            playerLVLDados = playerLVL;

            PlayerLevel();

            Debug.Log("LVL " + playerLVL);

        }



    }



    void Update()

    {

        if (Input.GetKeyDown(KeyCode.L))

        {            

            Experience();

        }



        positionPlayer = transform.position;

        if (Time.timeScale == 0)

        {            

            PlayerPosicao();

        }

    }

}
Script do player, básica apenas com alguns dados e funções para teste. A void PosicaoInicial seria invocada pelo próximo script...



Código:



using System.Collections;

using System.Collections.Generic;

using UnityEngine.UI;

using UnityEngine;

using System.Runtime.Serialization.Formatters.Binary;

using System.IO;

using System;

using UnityEngine.SceneManagement;



public class GameManager : MonoBehaviour {



    public static GameManager instance;

    private SaveGameData savedGame;

    private float barraStaminaDados;

    private const string File_Path = "saveGameData.dat";

    private bool isNewGame = false;

    private Vector3 positionPlayerDados;

    private int stageAnte,stageAtual, playerLVLdadosGM, playerXPdadosGM;

    private string stageAtualName;

    public static float valBarraStaminaInicial;





    // Use this for initialization 

    void Awake()

    {

        if (instance == null)

        {

            instance = this;

            DontDestroyOnLoad(gameObject);

        }

        else if (instance != null)

        {

            Destroy(gameObject);

        }



    }

    private void Start()

    {

        Load();

    }



    private void Update()

    {

        if(Time.timeScale==0)

        {

            stageAnte = SceneManager.GetActiveScene().buildIndex;

        }        

    }



    void OnEnable()

    {

        PLAYER.PlayerPosicao += OnPlayerPosicao;

        PLAYER.PlayerLevel += OnPlayerLevelGM;

        PLAYER.PlayerXP += OnPlayerXPGM;

        UIManager.StaminaControl += OnStaminaControl;

        SceneManager.sceneLoaded += OnStageLoad;

    }



    private void OnDisable()

    {

        PLAYER.PlayerPosicao -= OnPlayerPosicao;

        PLAYER.PlayerLevel -= OnPlayerLevelGM;

        PLAYER.PlayerXP -= OnPlayerXPGM;

        UIManager.StaminaControl -= OnStaminaControl;

        SceneManager.sceneLoaded -= OnStageLoad;

    }



    void OnPlayerXPGM()

    {

        playerXPdadosGM = PLAYER.xpPlayerDados;

    }



    void OnPlayerLevelGM()

    {

        playerLVLdadosGM = PLAYER.playerLVLDados;

    }



    void OnPlayerPosicao()

    {

        positionPlayerDados = PLAYER.positionPlayer;

    }



    void OnStaminaControl()

    {

        barraStaminaDados = UIManager.valBarraStamina;        

    }



    void OnStageLoad(Scene scene, LoadSceneMode mode)

    {



        if (isNewGame==false && savedGame!=null)

        {            

            UIManager.valBarraStamina = savedGame.barraStaminaSave;

            PLAYER.playerLVLDados = savedGame.splayerLVL;

            PLAYER.xpPlayerDados = savedGame.splayerXP;



            PLAYER.instance.transform.position = new Vector3(savedGame.spositionX, savedGame.spositionY, savedGame.spositionZ);



            //===================================Atualiza os Dados nos Respectivos Scripts=======================================================//



            PLAYER.instance.DadosAtual();

            UIManager.instance.UpdateUI();



            isNewGame = true;

        }

        else

        {



        }

    }



    void SceneControl()

    {

        stageAtualName = SceneManager.GetActiveScene().name;

        stageAtual= SceneManager.GetActiveScene().buildIndex;

        if (stageAtualName=="Main Menu")

        {

            stageAtual = stageAnte;

        }

    }



    public void SaveGame()

    {

        BinaryFormatter bf = new BinaryFormatter();

        FileStream file = File.Create(Path.Combine(Application.streamingAssetsPath, File_Path));



        SaveGameData save = new SaveGameData();

        save.barraStaminaSave = barraStaminaDados;



        save.spositionX = positionPlayerDados.x;

        save.spositionY = positionPlayerDados.y;

        save.spositionZ = positionPlayerDados.z;

        save.stage = stageAtual;

        save.splayerLVL = playerLVLdadosGM;

        save.splayerXP = playerXPdadosGM;



        bf.Serialize(file, save);



        file.Close();



    }



    public void Load()

    {

        if (File.Exists(Path.Combine(Application.streamingAssetsPath, File_Path)))

        {

            BinaryFormatter bf = new BinaryFormatter();

            FileStream file = File.Open(Path.Combine(Application.streamingAssetsPath, File_Path), FileMode.Open);



            SaveGameData save = (SaveGameData) bf.Deserialize(file);



            savedGame = save;



            file.Close();

        }



    }



    private void OnApplicationQuit()

    {

        SceneControl();

        SaveGame();

        positionPlayerDados = new Vector3(-781.5f, 1.2f, 110f);

        Debug.Log("OnApplicationQuit "+ positionPlayerDados);

    }



    public void NewGame()

    {

        PLAYER.positionPlayer = new Vector3(-780.5f, 1.2f, 110f);



        PLAYER.playerLVLDados = 1;

        PLAYER.xpPlayerDados = 0;

        valBarraStaminaInicial = 100;

        UIManager.valBarraStamina = valBarraStaminaInicial;



        PLAYER.instance.DadosAtual();

        PLAYER.instance.PosicaoInicial();

        UIManager.instance.UpdateUI();



        Debug.Log("teste");



        isNewGame = true;



        LoadStage(1);

    }





    public void LoadGame()

    {

        isNewGame = false;

        Load();

        LoadStage(savedGame.stage);



    }



    public void LoadStage(int stage)

    {

        SceneManager.LoadScene(stage);





    }



}





[Serializable]

class SaveGameData

{

    public float barraStaminaSave;



    public float spositionX;

    public float spositionY;

    public float spositionZ;



    public int stage;

    public int splayerLVL;

    public int splayerXP;

}
na função NewGame eu tentei "setar" alguns valores e testes... não funcionou. Pelos meus testes esta função só ativa o:
Código:
        isNewGame = true;

        LoadStage(1);
Este código esta muito bagunçado pois testei ativar, adicionar e desativar varias funções...
Por ultimo meu script de controle de UI... também mantem os dados salvos, não começa um jogo com novos dados.
Código:



using System.Collections;

using UnityEngine.UI;

using System.Collections.Generic;

using UnityEngine;

using System;



public class UIManager : MonoBehaviour {



    public static UIManager instance;



    public delegate void UICondicao();

    public static event UICondicao StaminaControl;





    public Slider barrastamina, barraDeVida;

    public float perda, ganho, gastStamina, ganhoStamina;

    public int QuantSede=0 , playerLVLDadosUI;

    private bool Sede=false;

    public static float valBarraStamina;





    // Use this for initialization

    void Awake()

    {

        if (instance == null)

        {

            instance = this;

        }

        else if (instance != null)

        {

            Destroy(gameObject);

        }      

    }



    private void OnEnable()

    {

        PLAYER.PlayerLevel += OnUIPlayerLevel;

    }



    private void OnDisable()

    {

        PLAYER.PlayerLevel -= OnUIPlayerLevel;

    }



    void OnUIPlayerLevel()

    {

        playerLVLDadosUI = PLAYER.playerLVLDados;

        gastStamina  = perda - playerLVLDadosUI / 200f;

        ganhoStamina = ganho + playerLVLDadosUI / 200f;

    }





    // Update is called once per frame



    void Update ()

    {





        if (Time.timeScale == 0 && valBarraStamina!=barrastamina.value)

        {

            valBarraStamina = (float)barrastamina.value;

            StaminaControl();

        }

        //===========================================Controle da Stamina===========================================//

        if (Time.timeScale > 0)

        {

            if (Input.GetKey(KeyCode.LeftShift))

            {

                if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D))

                {

                    barrastamina.value -= gastStamina;

                    QuantSede++;

                }

            }



            if (Input.GetKey(KeyCode.Space))

            {

                barrastamina.value -= gastStamina / 2;

                QuantSede++;

            }



            if (Input.GetKey(KeyCode.Mouse0))

            {

                barrastamina.value -= gastStamina / 2;

                QuantSede++;

            }



            if (Sede == false)

            {

                if (barrastamina.value > 2)

                {

                    if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D))

                    {

                        barrastamina.value += ganhoStamina / 3;

                    }

                    else

                    {

                        barrastamina.value += ganhoStamina;

                    }

                }

                else

                {

                    if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D))

                    {

                        barrastamina.value += ganhoStamina / 20;

                    }

                    else

                    {

                        barrastamina.value += ganhoStamina;

                    }

                }

            }

            if (QuantSede >= 15000)

            {

                Sede = true;

            }

            else

            {

                Sede = false;

            }



        }



    }

    public void UpdateUI()

    {

        barrastamina.value = valBarraStamina;

        Debug.Log("Update UI" + GameManager.valBarraStaminaInicial);        

    }
}


Agradeço se alguém puder me ajudar.
Na minha cena "Main Menu" eu "setei" a função New Game e Load em seus respectivos botões.

arnaldojunior
Membro
Membro

PONTOS : 2804
REPUTAÇÃO : 2
Respeito as regras : Salvar dados WvDYdlf

Ir para o topo Ir para baixo

DÚVIDA Re: Salvar dados

Mensagem por arnaldojunior Qui maio 24, 2018 6:39 am

Olá a todos, ainda continuo com esse problema em começar um novo jogo, mas fiz dezenas de testes (acho que centenas) e descobri que meu problema é no acionamento do button New Game.
como podem ver, a função new game tem várias definições, mas nenhuma é acionada.
Código:
 public void NewGame()[size=14][/size]    {[size=14][/size]        PLAYER.positionPlayer = new Vector3(-780.5f, 1.2f, 110f);[size=14][/size]        PLAYER.playerLVLDados = 1;[size=14][/size]        PLAYER.xpPlayerDados = 0;[size=14][/size]        valBarraStaminaInicial = 100;[size=14][/size]        UIManager.valBarraStamina = valBarraStaminaInicial;[size=14][/size]        PLAYER.instance.DadosAtual();[size=14][/size]        PLAYER.instance.PosicaoInicial();[size=14][/size]        UIManager.instance.UpdateUI();[size=14][/size]        Debug.Log("teste");[size=14][/size]        isNewGame = true;[size=14][/size]        LoadStage(1);
}[size=14][/size][b][/b][i][/i][u][/u][sub][/sub][sup][/sup][strike][/strike]


Somente a void LoadStage é ativada. Alguém sabe me dizer o motivo?
O interessante que o button Carregar, que possui o script:

Código:
    public void LoadGame()[size=14][/size]    {[size=14][/size]        isNewGame = false;[size=14][/size]        Load();[size=14][/size]        LoadStage(savedGame.stage);[size=14][/size]    }[b][/b][i][/i][u][/u][sub][/sub][sup][/sup][strike][/strike]
funciona perfeitamente, e ambos estão configurados da mesma maneira.
Agradeço se alguém puder me explicar esse Bug.

arnaldojunior
Membro
Membro

PONTOS : 2804
REPUTAÇÃO : 2
Respeito as regras : Salvar dados WvDYdlf

Ir para o topo Ir para baixo

Ir para o topo

- Tópicos semelhantes

 
Permissões neste sub-fórum
Não podes responder a tópicos