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

Unity C# - On button click pass gameobject to another C# script

我有多个按钮,它们附有不同的游戏对象。 单击按钮时,我想将游戏对象传递给另一个 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}\'" );
        }
    }
}