如何解决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}\'" );
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。