Unity C# - 单击按钮将游戏对象传递给另一个 C# 脚本 [关闭]
Posted
技术标签:
【中文标题】Unity C# - 单击按钮将游戏对象传递给另一个 C# 脚本 [关闭]【英文标题】:Unity C# - On button click pass gameobject to another C# script [closed] 【发布时间】:2021-02-03 18:38:12 【问题描述】:我有多个按钮,它们附加了不同的游戏对象。 单击按钮时,我想将游戏对象传递给另一个 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;
【问题讨论】:
【参考方案1】:它可以像让第二个脚本公开您可以将对象传递到的字段或属性一样简单。执行此操作的多种方法之一可能如下所示:
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\'" );
【讨论】:
Milan 感谢您的回答,但我在控制台中收到此错误:NullReferenceException: Object reference not set to an instance of an object Element.PassObjectToAnotherScript () (at Assets/Scripts/Element.cs :21) @Hamza 您是否将接收器组件添加到对象,然后将该对象拖到“元素”组件的“接收器”字段中? 非常感谢。我已经完成了您回复我的操作,并且有效。非常感谢。以上是关于Unity C# - 单击按钮将游戏对象传递给另一个 C# 脚本 [关闭]的主要内容,如果未能解决你的问题,请参考以下文章
通过单击Eclipse中的“运行”按钮安装apk时如何将参数传递给ADB?