Форум программистов, компьютерный форум, киберфорум
Unity, Unity3D
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.50/4: Рейтинг темы: голосов - 4, средняя оценка - 4.50
 Аватар для NotGoodEnough
34 / 30 / 8
Регистрация: 22.02.2017
Сообщений: 404

Форумчане, спасайте! Сижу 3 дня с этих багом разобраться не могу

02.03.2018, 18:30. Показов 825. Ответов 8
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Вот видео о баге.
https://vimeo.com/258279915

Вот скрипты:
Inventory:
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
using UnityEngine;
using UnityEngine.UI;
using UnityStandardAssets.Characters.FirstPerson;
using System.Collections.Generic;
 
public class Inventory : MonoBehaviour {
 
    #region Singleton
    private static Inventory instance;
    public static Inventory Instance
    {
        get { return instance; }
        set { instance = value; }
    }
    private void Awake()
    {
        instance = this;
    }
    #endregion
 
    public KeyCode inventoryKey = KeyCode.Tab;
    public GameObject inventory;
    public Transform conatiner;
    public ItemInfo itemInfo;
    public Dictionary<int, Item> items = new Dictionary<int, Item>();
    // public List<Item> items = new List<Item>();
    public List<InventorySlot> slots = new List<InventorySlot>();
    public List<HotBatSlot> hotBarSlots = new List<HotBatSlot>();
 
    private FirstPersonController firstPerson;
 
    private void Start()
    {
        firstPerson = GetComponent<FirstPersonController>();
 
        inventory.SetActive(false);
        CursorLock.ChangeLock(true);
 
        for (int i = 0; i < conatiner.childCount; i++)
        {
            slots.Add(conatiner.GetChild(i).GetComponent<InventorySlot>());
            slots[i].index = i;
        }
    }
 
    private void Update()
    {
        if (Input.GetKeyDown(inventoryKey))
        {
            firstPerson.m_MouseLookActive = inventory.activeSelf;
            inventory.SetActive(!inventory.activeSelf);
            if (!Craft.Instance.craft.activeSelf)
                CursorLock.ChangeLock(!inventory.activeSelf);
        }
    }
 
    public void AddItem(Item item, int count)
    {
        for (int i = 0; i < slots.Count; i++)
        {
            if (slots[i].isEmpty)
            {
                items.Add(slots[i].index, item);
                // items.Add(item);
                slots[i].item = item;
                slots[i].count = count;
                slots[i].isEmpty = false;
                GameObject newItem = Instantiate(slots[i].iconPrefab, Vector2.zero, Quaternion.identity) as GameObject;
                newItem.GetComponent<Image>().sprite = item.icon;
                newItem.transform.SetParent(slots[i].transform);
                newItem.name = newItem.name + ", " + slots[i].index;
                break;
            }
            else Debug.Log("Inventory full");
        }
    }
 
    public void AddItemInCertainSlot(Item item, int count, int index)
    {
        for (int i = 0; i < slots.Count; i++)
        {
            if (i == index)
            {
                items.Add(slots[i].index, item);
                // items.Add(item);
                slots[i].item = item;
                slots[i].count = count;
                slots[i].isEmpty = false;
                GameObject newItem = Instantiate(slots[i].iconPrefab, Vector2.zero, Quaternion.identity) as GameObject;
                newItem.GetComponent<Image>().sprite = item.icon;
                newItem.transform.SetParent(slots[i].transform);
                newItem.name = newItem.name + ", " + slots[i].index;
                break;
            }
        }
    }
 
    public void RemoveItem(Item item)
    {
        for (int i = 0; i < slots.Count; i++)
        {
            if (slots[i].item == item)
            {
                items.Remove(slots[i].index);
                // items.Remove(item);
                if (slots[i].transform.childCount > 0)
                    Destroy(slots[i].transform.GetChild(0).gameObject);
                slots[i].item = null;
                break;
            }
        }
    }
}
InventorySlot:
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
using UnityEngine;
using UnityEngine.UI;
 
public class InventorySlot : MonoBehaviour {
 
    public int index;
 
    public Item item;
    public DragAndDrop dragAndDrop;
    public int count;
    public bool isEmpty = true;
    public GameObject iconPrefab;
 
    private Text counter;
    private GameObject icon;
 
    private void Update()
    {
        if (item)
        {
            isEmpty = false;
            if (transform.childCount == 1)
            {
                dragAndDrop = transform.GetChild(0).GetComponent<DragAndDrop>();
                icon = transform.GetChild(0).gameObject;
                counter = icon.GetComponentInChildren<Text>();
                counter.text = count.ToString();
                if (count > 1)
                    counter.enabled = true;
                else counter.enabled = false;
            }
        }
        else
        {
            isEmpty = true;
            item = null;
            dragAndDrop = null;
            counter = null;
            count = 0;
            icon = null;
        }
    }
}
DragAndDrop:
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
 
public class DragAndDrop : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler, IPointerClickHandler {
 
    public Item tmpItem;
    public int tmpCount;
 
    private ItemInfo itemInfo;
    private Transform oldParent;
    private Transform canvas;
    private Image image;
    private Inventory inventory;
    private InventorySlot inventorySlot;
    // private Item inventorySlotItem;
    // private int inventorySlotCount;
    private Transform icon;
 
    private void Start()
    {
        canvas = GameObject.FindWithTag("Canvas").transform;
        inventory = Inventory.Instance;
        itemInfo = inventory.itemInfo;
        // inventorySlot = transform.parent.GetComponent<InventorySlot>();
        image = GetComponent<Image>();
    }
 
    private void Update()
    {
        if (transform.parent.GetComponent<InventorySlot>())
            inventorySlot = transform.parent.GetComponent<InventorySlot>();
    }
 
    public void OnBeginDrag(PointerEventData eventData)
    {
        if (eventData.button == PointerEventData.InputButton.Left)
        {
            image.raycastTarget = false;
            // inventorySlot = transform.parent.GetComponent<InventorySlot>();
            // inventorySlotItem = inventorySlot.item;
            // inventorySlotCount = inventorySlot.count;
            tmpItem = inventorySlot.item;
            tmpCount = inventorySlot.count;
            oldParent = transform.parent;
            transform.SetParent(canvas);
            Debug.Log(inventorySlot.item.name + " index: " + inventorySlot.index);
        }
        else if (eventData.button == PointerEventData.InputButton.Middle && inventorySlot.count > 1)
        {
            icon = Instantiate(inventorySlot.iconPrefab, Vector2.zero, Quaternion.identity).transform;
            icon.GetComponent<Image>().raycastTarget = false;
            icon.GetComponent<Image>().sprite = inventorySlot.item.icon;
            icon.GetComponent<DragAndDrop>().tmpItem = inventorySlot.item;
            icon.GetComponent<DragAndDrop>().tmpCount = inventorySlot.count;
            icon.transform.SetParent(canvas);
            Text iconText = icon.GetComponentInChildren<Text>();
            int calculatedCount = inventorySlot.count / 2;
            iconText.text = calculatedCount.ToString();
            if (calculatedCount > 1)
                iconText.enabled = true;
            else iconText.enabled = false;
            inventorySlot.count -= calculatedCount;
            Debug.Log("Splitted: " + inventorySlot.item + ", " + calculatedCount);
            Debug.Log(inventorySlot.item.name + " index: " + inventorySlot.index);
        }
    }
 
    public void OnDrag(PointerEventData eventData)
    {
        if (eventData.button == PointerEventData.InputButton.Left)
            transform.localPosition = Input.mousePosition - new Vector3(Screen.width / 2, Screen.height / 2, 0);
        if (eventData.button == PointerEventData.InputButton.Middle && inventorySlot.count >= 1 && icon != null)
            icon.transform.localPosition = Input.mousePosition - new Vector3(Screen.width / 2, Screen.height / 2, 0);
    }
 
    public void OnEndDrag(PointerEventData eventData)
    {
        if (eventData.button == PointerEventData.InputButton.Left)
        {
            image.raycastTarget = true;
 
            if (eventData.pointerCurrentRaycast.gameObject != null)
            {
                if (eventData.pointerCurrentRaycast.gameObject.transform.parent == canvas)
                    transform.SetParent(oldParent);
                else if (eventData.pointerCurrentRaycast.gameObject.GetComponent<DragAndDrop>())
                {
                    InventorySlot newInventorySlot = eventData.pointerCurrentRaycast.gameObject.transform.parent.GetComponent<InventorySlot>();
                    inventorySlot.item = newInventorySlot.item;
                    inventorySlot.count = newInventorySlot.count;
                    eventData.pointerCurrentRaycast.gameObject.transform.SetParent(oldParent);
 
                    transform.SetParent(newInventorySlot.transform);
                    inventorySlot = transform.parent.GetComponent<InventorySlot>();
                    // inventorySlot.item = inventorySlotItem;
                    // inventorySlot.count = inventorySlotCount;
                    inventorySlot.item = tmpItem;
                    inventorySlot.count = tmpCount;
                }
                else
                {
                    if (eventData.pointerCurrentRaycast.gameObject.transform != oldParent)
                    {
                        InventorySlot newInventorySlot = eventData.pointerCurrentRaycast.gameObject.GetComponent<InventorySlot>();
                        newInventorySlot.item = inventorySlot.item;
                        newInventorySlot.count = inventorySlot.count;
                        inventorySlot.item = null;
                    }
                    transform.SetParent(eventData.pointerCurrentRaycast.gameObject.transform);
                }
            }
            else
            {
                DropItem();
            }
 
            inventorySlot = transform.parent.GetComponent<InventorySlot>();
        }
        else if (eventData.button == PointerEventData.InputButton.Middle && inventorySlot.count >= 1 && icon != null)
        {
            icon.GetComponent<Image>().raycastTarget = true;
 
            if (eventData.pointerCurrentRaycast.gameObject != null)
            {
                if (eventData.pointerCurrentRaycast.gameObject.transform.parent != oldParent && eventData.pointerCurrentRaycast.gameObject.transform.parent != canvas)
                {
                    if (eventData.pointerCurrentRaycast.gameObject.transform.parent.GetComponent<InventorySlot>())
                    {
                        InventorySlot newInventorySlot = eventData.pointerCurrentRaycast.gameObject.transform.parent.GetComponent<InventorySlot>();
                        if (newInventorySlot.item == inventorySlot.item)
                        {
                            newInventorySlot.count += int.Parse(icon.GetComponentInChildren<Text>().text);
                            Destroy(icon.gameObject);
                        }
                    }
                    else
                    {
                        InventorySlot newInventorySlot = eventData.pointerCurrentRaycast.gameObject.GetComponent<InventorySlot>();
                        newInventorySlot.item = inventorySlot.item;
                        newInventorySlot.count = int.Parse(icon.GetComponentInChildren<Text>().text);
                        inventory.AddItemInCertainSlot(inventorySlot.item, newInventorySlot.count, newInventorySlot.index);
                        // inventory.items.Add(inventorySlot.index, inventorySlot.item);
                        icon.SetParent(eventData.pointerCurrentRaycast.gameObject.transform);
                        Destroy(icon.gameObject);
                    }
                }
                else
                {
                    inventorySlot.count += int.Parse(icon.GetComponentInChildren<Text>().text);
                    Destroy(icon.gameObject);
                }
            }
            else
            {
                // DropItem(inventorySlot.item);
                Destroy(icon.gameObject);
                Debug.Log("Now don't work!");
            }
            icon = null;
        }
    }
 
    public void OnPointerClick(PointerEventData eventData)
    {
        if (eventData.button == PointerEventData.InputButton.Left)
        {
            itemInfo.gameObject.SetActive(true);
            itemInfo.UpdateInfo(inventorySlot.item);
        }
        else if (eventData.button == PointerEventData.InputButton.Right)
        {
            if (inventorySlot.count == 1)
                inventorySlot.item.Use(inventorySlot.count);
            else
            {
                inventorySlot.item.Use(inventorySlot.count);
                inventorySlot.count -= 1;
            }
        }
    }
 
    public void DropItem()
    {
        InventorySlot dropInventorySlot = oldParent.GetComponent<InventorySlot>();
        GameObject newItem = Instantiate(dropInventorySlot.item.prefab, inventory.transform.position + inventory.transform.forward, Quaternion.identity) as GameObject;
        PickUp itemPickUp = newItem.GetComponent<PickUp>();
        itemPickUp.count = dropInventorySlot.count;
        inventory.RemoveItem(dropInventorySlot.item);
        Destroy(gameObject); // ИСПРАВИТЬ ИСПРАВИТЬ ИСПРАВИТЬ ИСПРАВИТЬ ИСПРАВИТЬ ИСПРАВИТЬ ИСПРАВИТЬ ИСПРАВИТЬ ИСПРАВИТЬ ИСПРАВИТЬ ИСПРАВИТЬ ИСПРАВИТЬ ИСПРАВИТЬ ИСПРАВИТЬ ИСПРАВИТЬ ИСПРАВИТЬ
        Debug.Log(dropInventorySlot.item + " dropped, and removed from inventory.");
    }
}
0
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
02.03.2018, 18:30
Ответы с готовыми решениями:

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

уважаемые форумчане не могу разобраться с перегрузкой
задание такое: выполнить перегрузку перечисленных операций, закрепив за ними соответствующий функциональный смысл. Строка символов. ^ -...

Новый комп. Почти чистая винда. Два синих экрана за два дня. Не могу разобраться
Новый комп. Почти чистая винда. Два синих экрана за два дня. Вылетают синие экраны при закрытии БФ4, ( может совпадение)... Прикладываю...

8
58 / 57 / 15
Регистрация: 15.09.2012
Сообщений: 557
02.03.2018, 20:58
так вникать долго - проект в студию
0
 Аватар для NotGoodEnough
34 / 30 / 8
Регистрация: 22.02.2017
Сообщений: 404
02.03.2018, 22:34  [ТС]
Проект весит 1.7 Гб...
Почищу и скину, завтра =)
0
 Аватар для Serj190492
160 / 159 / 59
Регистрация: 19.02.2015
Сообщений: 830
03.03.2018, 06:56
NotGoodEnough, папку Library можно в архиве удалить, заметно меньше станет
0
 Аватар для NotGoodEnough
34 / 30 / 8
Регистрация: 22.02.2017
Сообщений: 404
03.03.2018, 16:37  [ТС]
Вот, папка Assets
https://yadi.sk/d/iEUsn8rP3Sy53B
0
58 / 57 / 15
Регистрация: 15.09.2012
Сообщений: 557
03.03.2018, 21:20
NotGoodEnough, как ты там разбил шарик на 3 и 2 единицы при перетаскивании на другой слот. У меня 5 единиц и остается - перносится в другой слот
0
 Аватар для NotGoodEnough
34 / 30 / 8
Регистрация: 22.02.2017
Сообщений: 404
03.03.2018, 22:46  [ТС]
Средняя кнопка мыши! Просишь проект если даже в коде разобраться не можешь...
0
58 / 57 / 15
Регистрация: 15.09.2012
Сообщений: 557
04.03.2018, 10:27
Вобщем код адский. Например код InventorySlot
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 private void Update()
    {
        if (item)
        {
            isEmpty = false;
            if (transform.childCount == 1)
            {
                dragAndDrop = transform.GetChild(0).GetComponent<DragAndDrop>();
                icon = transform.GetChild(0).gameObject;
                counter = icon.GetComponentInChildren<Text>();
                counter.text = count.ToString();
                if (count > 1)
                    counter.enabled = true;
                else counter.enabled = false;
            }
        }
Вместо того чтобы один раз проинициализировать слот положенным обьектом - все происходит в цыкле без останова.
И подобных моментов множество, вложенность if 5 штук) В целом код нужно кардинально переписывать иначе так и будет поиск каждого бага по неделле

По поводу твоего бага - при дропе из слота вызываешь DropItem, он же вызывает inventory.RemoveItem(dropInventorySlot.i tem);
А dropInventorySlot.item - у тебя на всех InventorySlot одинаковый - это ссылка на один и тот же обькт. По этому когда перетаскиваешь из второго слота - удальется первый в очереди и срабатывает брек.
0
 Аватар для NotGoodEnough
34 / 30 / 8
Регистрация: 22.02.2017
Сообщений: 404
04.03.2018, 14:04  [ТС]
Я понимаю что с оптимизацией кода проблемы, я пока только делаю основу, после буду всё оптимизировать и править баги которые вылезут при оптимизации кода.

И на счёт цикла в InventorySlot, Update вызывается только когда инвентарь открыт (но когда дойду до оптимизации уберу этит цикл).
Баг я исправил.

И да, не подскажете как лучше реализовать Craft?
Я думал делать так:
Сделать панель со списком кнопок, кнопки - предметы.
При нажатии на кнопку будет открываться окно с описанием, стоимостью крафта данного предмета и т.д.
В этом окошке будет кнопка крафта при нажатии на которую будут отниматься предметы и запускаться короутина, ну а дальше после окончания короутины добавление предмета.
Но я не знаю как можно правильно реализавть поиск нужных предметов для крафта в инвентаре?

Как вы думаете?
Так же если не сложно пару советов по оптимизации кода =)

Вот как всё работает (разделение предметов)
https://vimeo.com/258476251
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
04.03.2018, 14:04
Помогаю со студенческими работами здесь

Задали работу, не могу разобраться. Используется делфи 10, не могу разобраться, как это сделать
В одномерном массиве, состоящем из n вещественных элементов, вычислить: минимальный элемент массива и сумму элементов массива,...

Какой день сижу, не могу понять:(
{ссылка удалена}

Не могу дописать программу, сижу с самого утра
Відомі дані про місткості (в мегабайтах ) і вартості (в гривні) кожного з 22 типів жорстких магнітних дисків (вінчестерів) надрукувати...

Не могу дописать программу, сижу с самого утра
Реализовать игру &quot;Отгадай слово&quot; , которая происходит следующим образом. Машина загадывает слово (случайным образом выбирает его из...

не могу написать программу, сижу с самого утра
Дано двовимірний масив, що місить 6 рядки та 4 стовпчиків. Елементами масиву є цілі числа. Впорядкувати масив по зростанню елементів...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
9
Ответ Создать тему
Новые блоги и статьи
Загрузка PNG-файла с альфа-каналом с помощью библиотеки SDL3_image на Android
8Observer8 27.01.2026
Содержание блога SDL3_image - это библиотека для загрузки и работы с изображениями. Эта пошаговая инструкция покажет, как загрузить и вывести на экран смартфона картинку с альфа-каналом, то есть с. . .
влияние грибов на сукцессию
anaschu 26.01.2026
Бифуркационные изменения массы гриба происходят тогда, когда мы уменьшаем массу компоста в 10 раз, а скорость прироста биомассы уменьшаем в три раза. Скорость прироста биомассы может уменьшаться за. . .
Воспроизведение звукового файла с помощью SDL3_mixer при касании экрана Android
8Observer8 26.01.2026
Содержание блога SDL3_mixer - это библиотека я для воспроизведения аудио. В отличие от инструкции по добавлению текста код по проигрыванию звука уже содержится в шаблоне примера. Нужно только. . .
Установка Android SDK, NDK, JDK, CMake и т.д.
8Observer8 25.01.2026
Содержание блога Перейдите по ссылке: https:/ / developer. android. com/ studio и в самом низу страницы кликните по архиву "commandlinetools-win-xxxxxx_latest. zip" Извлеките архив и вы увидите. . .
Вывод текста со шрифтом TTF на Android с помощью библиотеки SDL3_ttf
8Observer8 25.01.2026
Содержание блога Если у вас не установлены Android SDK, NDK, JDK, и т. д. то сделайте это по следующей инструкции: Установка Android SDK, NDK, JDK, CMake и т. д. Сборка примера Скачайте. . .
Использование SDL3-callbacks вместо функции main() на Android, Desktop и WebAssembly
8Observer8 24.01.2026
Содержание блога Если вы откроете примеры для начинающих на официальном репозитории SDL3 в папке: examples, то вы увидите, что все примеры используют следующие четыре обязательные функции, а. . .
моя боль
iceja 24.01.2026
Выложила интерполяцию кубическими сплайнами www. iceja. net REST сервисы временно не работают, только через Web. Написала за 56 рабочих часов этот сайт с нуля. При помощи perplexity. ai PRO , при. . .
Модель сукцессии микоризы
anaschu 24.01.2026
Решили писать научную статью с неким РОманом
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru