Unity C#-在按钮上单击将游戏对象传递给另一个C#脚本

问题描述

我有多个带有不同游戏对象的按钮。 当单击按钮时,我想将游戏对象传递给另一个C#脚本,该脚本将在某些条件下实例化传递的游戏对象。 我的按钮有以下代码

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

public class Element : MonoBehavIoUr
{
    private Button btn;
    public GameObject furniture;
    // Start is called before the first frame update
    void Start()
    {
        btn = GetComponent<Button>();
        btn.onClick.AddListener(PassObjectToAnotherScript);
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    void PassObjectToAnotherScript()
    {
        //Code to pass the object to another C# script
    }
}

游戏对象必须传递到的C#脚本应具有:

private GameObject PassedGameObject;

解决方法

就像让第二个脚本公开可以将对象传递到的字段或属性那样简单。做到这一点的许多方法之一可能是这样的:

public class Element : MonoBehaviour
{
    private Button btn;
    public GameObject furniture;
    public Receiver recevier;

    void Start ( )
    {
        btn = GetComponent<Button> ( );
        btn.onClick.AddListener ( PassObjectToAnotherScript );
    }

    void PassObjectToAnotherScript ( )
    {
        //Code to pass the object to another C# script
        recevier.PassedGameObject = furniture;
    }
}

public class Receiver : MonoBehaviour
{
    private GameObject _PassedGameObject;
    public GameObject PassedGameObject
    {
        get => _PassedGameObject;
        set
        {
            _PassedGameObject = value;
            Debug.Log ( $"Receiver[{name}] just received \'{_PassedGameObject.name}\'" );
        }
    }
}