【问题标题】:Executing a Function Between Script Files在脚本文件之间执行函数
【发布时间】:2022-08-15 04:08:50
【问题描述】:

请告诉我。我有 2 个脚本挂在不同的 Unity 对象上。第一个脚本用于单击按钮。第二个用于执行功能。 如果按下按钮,如何执行 AddItem 函数?

脚本 1(按钮单击):

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

public class UseButton : MonoBehaviour, IPointerUpHandler, IPointerDownHandler
{
    public bool isClick = false;
 
    public void OnPointerDown(PointerEventData ped) 
    {
        isClick = true;

    }
    public void OnPointerUp(PointerEventData ped) 
    {

        isClick = false;
    }
}

脚本 2(添加项目):

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class InventoryManager : MonoBehaviour
{
    public void AddItem(ItemScriptableObject _item, int _amount)
    {

        

        foreach(InventorySlot slot in slots)
        {
            if (slot.item == _item)
            {
                slot.amount += _amount;
                return;
            }
        }
        foreach(InventorySlot slot in slots)
        {
            //print(_item+\" \"+_amount);
            if (slot.isEmpty == true)
            {
                slot.item = _item;
                slot.amount = _amount;
                slot.isEmpty = false;
                slot.SetIcon(_item.icon);
                return; 
            }
        }
    }
  • 可以说,更好的方法之一是让您的 isclick 成为一个属性并拥有一个事情可以订阅的事件。然后,您可以安全地做任何您喜欢 onclick 的事情。
  • @BugFinder 你能举个例子吗?
  • 我不是想在手机上打出一个完整的例子。谷歌属性和事件。

标签: c# unity3d


【解决方案1】:

如果您在第一个脚本的第二个脚本上没有变量,您应该使用以下方法来做到这一点:

GameObject go;
go.GetComponent<InventoryManager>();

尝试将第一个脚本更改为:

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

public class UseButton : MonoBehaviour, IPointerUpHandler, IPointerDownHandler
{
    public bool isClick = false;
    
    void Update() 
    {
         if (isClick)
         {
              Debug.Log("do something")
         }
    }
    public void OnPointerDown(PointerEventData ped) 
    {
        isClick = true;

    }
    public void OnPointerUp(PointerEventData ped) 
    {

        isClick = false;
    }
}

这样你就可以修改变量:很容易点击。

【讨论】:

    猜你喜欢
    • 2016-04-11
    • 1970-01-01
    • 2015-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-16
    相关资源
    最近更新 更多