Как я могу сделать так, чтобы деньги росли, а не повторялись? - PullRequest
0 голосов
/ 05 ноября 2019

Итак, я создаю 2D-игру в единстве, используя c #. Прямо сейчас, когда я играю в игру и забираю драгоценный камень, деньги идут от 0 до 1, и если я беру другой драгоценный камень, он снова делает 0 к 1, я не уверен, почему он продолжает возвращаться к 0. Что я могу изменить, чтобы сделатьпоэтому, когда я забираю драгоценные камни, деньги увеличиваются и убедитесь, что они работают с savesystem. У меня есть 4 сценария: GemPickup, Player, Playerdata и SaveSystem.

Пожалуйста, помогите, поскольку мне нужно разобраться с этим, как только я должен закончить игру к концу ноября.

Сценарий GemPickup:

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

public class Gempickup : Player
{
    public void OnTriggerEnter2D(Collider2D Collision)
    {
        if (Collision.gameObject.tag.Equals("Player"))
        {

            Destroy(gameObject);
            money = money + 1;



        }

    }
}

Сценарий игрока:

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

public class Player : MonoBehaviour
{
    public int level;
    public int health;
    public int money;


    public void Update()
    {
        if (Input.GetKeyDown("k"))
        {
            SaveSystem.SavePlayer(this);
        }

        if (Input.GetKeyDown("l"))
        {
            PlayerData data = SaveSystem.Loadplayer();

            level = data.level;
            health = data.health;
            money = data.money;

            Vector3 position;
            position.x = data.position[0];
            position.y = data.position[1];
            position.z = data.position[2];
            transform.position = position;
        }


    }
}

Сценарий PlayerData:

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

[System.Serializable]
public class PlayerData
{
    public int level;
    public int health;
    public int money;
    public float[] position;

    public PlayerData(Player player)
    {
        level = player.level;
        health = player.health;
        money = player.money;

        position = new float[3];
        position[0] = player.transform.position.x;
        position[1] = player.transform.position.y;
        position[2] = player.transform.position.z;

    }
}

Сценарий SaveSystem:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

public static class SaveSystem
{
    public static void SavePlayer (Player player)
    {
        BinaryFormatter formatter = new BinaryFormatter();
        string path = Application.persistentDataPath + "/player.fun";
        FileStream stream = new FileStream(path, FileMode.Create);

        PlayerData data = new PlayerData(player);

        formatter.Serialize(stream, data);
        stream.Close();
    }

    public static PlayerData Loadplayer()
    {
        string path = Application.persistentDataPath + "/player.fun";
        if (File.Exists(path))
        {
            BinaryFormatter formatter = new BinaryFormatter();
            FileStream stream = new FileStream(path, FileMode.Open);

            PlayerData data = formatter.Deserialize(stream) as PlayerData;
            stream.Close();

            return data;

        }

        else
        {
            Debug.LogError("Save file not found in" + path);
            return null;
        }
    }
}

Ответы [ 2 ]

1 голос
/ 05 ноября 2019

попробуйте это в скрипте игрока вместо прикрепления скрипта к игровому объекту gem. просто добавьте тег Gem в gem.

public void OnTriggerEnter2D(Collider2D Collision)
{
    if (Collision.gameObject.tag.Equals("Gem"))
    {

        Destroy(Collision.gameObject);
        money = money + 1;



    }

}
0 голосов
/ 05 ноября 2019

Чтобы не оставлять вас в покое, и, кроме того, я не использую Unity, я просто хочу показать вам следующий код. Вот как я мог бы создать его без единства.

public class Game
{

    public class GameObject
    {
        internal float[] position;

    }

    static public void Destroy(GameObject go)
    {
        // some object destruction
    }

    public class Gem : GameObject
    {
        // inherits position
    }

    public class Character : GameObject
    {
        // inherits position
        internal int health;
    }

    public class Enemy : Character
    {
        // inherits position and health
        public void OnCollision(GameObject other)
        {
            if (other is Player)
            {
                health--;
                if (health==0)
                {
                    Destroy(this);
                }
            }
        }
    }

    [System.Serializable]
    public class Player : Character
    {
        // inherits position and health
        // don't expose your internals
        // and probably should be properties.. but I don't know if they work with the serializer
        internal int level;
        internal int money;

        public void OnCollision(GameObject other)
        {
            if (other is Gem)
            {
                Destroy(other);
                money++;
            }
            else if (other is Enemy)
            {
                health--;
                if (health == 0)
                {
                    //game over;
                }
            }
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...