传递一个类型为CustomClass的数组给由按钮的OnClick调用的方法如何做?

huangapple go评论48阅读模式
英文:

How pass an Array of type CustomClass to a method called by a buttons OnClick?

问题

我想根据按下的按钮将 Hackable(自定义类)传递到主游戏中的小游戏中。然而,onclick 不列出接受 Hackable[] hackables 作为参数的方法。我认为它可能在处理参数类型上有困难 - 我的自定义类 hackable。有没有解决方法?

更多信息

我有一个脚本在整个时间内运行。只有在“hacking-panel”打开时,脚本才会运行一个小型迷你游戏。在打开面板之前,我想设置对象(hackable)在玩家成功完成迷你游戏后被黑客入侵。

我也考虑每次开始黑客时创建这个小游戏,但我不确定在Unity中如何实现这一点。无论哪种情况,我都需要将 hackable 传递给一个方法或构造函数,以了解正在被黑客入侵的是什么。

英文:

I would like to pass Hackables (custom class) into a mini-game within the main game depending on the button that is pressed. However, onclick doesn't list my method that takes Hackable[] hackables as a parameter. I think it might be struggeling with the parameter type - my custom class hackable. Any ideas how to solve this?

More information

I have a script that runs the entire time. Only if the "hacking-panel" is open, the script runs a small mini-game. Before the panel is opened, I want to set the objects (hackables) that are hacked if the player succeeds at finishing the mini-game.

I also thought about creating this mini-game everytime a hack is started, but I wasn't sure how this would work in unity. In every case I need to pass the hackables into a method or constructor in order to know what's beeing hacked.

答案1

得分: 1

onclick方法不支持自定义类参数。您只能传递原始类型、字符串或UnityEngine.Object类型1。

一个可能的解决方案是使用委托或Lambda表达式将您的方法调用与自定义类参数包装起来。例如,您可以这样做:

// 假设您有对按钮和hackables数组的引用
button.onClick.AddListener(() => YourMethod(hackables));

这样,您可以将hackables数组传递给您的方法,而不使用onclick参数1。

英文:

onclick method doesn’t support custom class parameters. You can only pass primitive types, strings, or UnityEngine.Object types1.

One possible solution is to use delegates or lambda expressions to wrap your method call with the custom class parameter. For example, you can do something like this:

// Assuming you have a reference to your button and your hackables array
button.onClick.AddListener(() => YourMethod(hackables));

This way, you can pass your hackables array to your method without using the onclick parameter1.

huangapple
  • 本文由 发表于 2023年5月29日 01:27:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76352721.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定