我对在 Unity 上创建手机游戏还很陌生,所以我最近遇到了一个问题。 我的库存需要一个项目(用于治疗玩家的急救),当游戏在统一运行时,我按下设备模拟器设备包上的项目并且它工作(Debug.Log 显示它正在控制台上使用)。我构建并运行到我的模拟器(LD 播放器)上,但项目功能不起作用。它显示按钮正在被按下,但由于某种原因该功能没有运行。
public void UseItem()
{
//Use the healing pack
if(item != null)
{
Debug.Log("Healing has occured!");
//Heal the player by a certain amount, then delete item.
item.Heal(healAmount, player);
item.RemoveFromInventory();
}
}
玩家有一个 Heal() 函数,可以将玩家当前的生命值增加一定数量并相应地修改生命值条。
public void RemoveFromInventory()
{
//remove the item from the inventory.
Inventory.instance.Remove(this);
}
public void Remove(Item item)
{
//Remove the item from the list.
items.Remove(item);
if (onItemChangedCallback != null)
{
onItemChangedCallback.Invoke();
}
}
更新: 我通过 Android Studio 运行 logcat,得到的错误是
2021-04-05 12:19:35.119 3615-3634/? I/Unity: Healing has occured!
UnityEngine.Logger:Log(LogType, Object)
InventorySlot:UseItem()
UnityEngine.Events.UnityAction:Invoke()
UnityEngine.Events.UnityEvent:Invoke()
UnityEngine.EventSystems.EventFunction`1:Invoke(T1, BaseEventData)
UnityEngine.EventSystems.ExecuteEvents:Execute(GameObject, BaseEventData, EventFunction`1)
UnityEngine.EventSystems.StandaloneInputModule:ProcessTouchPress(PointerEventData, Boolean, Boolean)
UnityEngine.EventSystems.StandaloneInputModule:ProcessTouchEvents()
UnityEngine.EventSystems.StandaloneInputModule:Process()
2021-04-05 12:19:35.123 3615-3634/? E/Unity: NullReferenceException: Object reference not set to an instance of an object.
at Item.Heal (System.Int32 amount, PlayerBehavior currentPlayer) [0x00000] in <00000000000000000000000000000000>:0
at InventorySlot.UseItem () [0x00000] in <00000000000000000000000000000000>:0
at UnityEngine.Events.UnityAction.Invoke () [0x00000] in <00000000000000000000000000000000>:0
at UnityEngine.Events.UnityEvent.Invoke () [0x00000] in <00000000000000000000000000000000>:0
at UnityEngine.EventSystems.ExecuteEvents+EventFunction`1[T1].Invoke (T1 handler, UnityEngine.EventSystems.BaseEventData eventData) [0x00000] in <00000000000000000000000000000000>:0
at UnityEngine.EventSystems.ExecuteEvents.Execute[T] (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.ExecuteEvents+EventFunction`1[T1] functor) [0x00000] in <00000000000000000000000000000000>:0
at UnityEngine.EventSystems.StandaloneInputModule.ProcessTouchPress (UnityEngine.EventSystems.PointerEventData
这很奇怪,因为我设置了 Start() 函数来搜索带有“玩家”标签的游戏对象,然后从该玩家那里获取脚本。
最终更新: 我更改了我的 Heal() 函数,以便每当它被调用时,我都会搜索播放器,现在它可以正常工作了。
public virtual void Heal(int amount, PlayerBehavior currentPlayer)
{
currentPlayer = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerBehavior>();
//increase the player health by the amount the pack gives.
currentPlayer.HealDamage(amount);
}