C# Unity2D 是否可以基于字符串调用脚本? [英] C# Unity2D Is it possible to call a script based on a string?

查看:51
本文介绍了C# Unity2D 是否可以基于字符串调用脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在从文本变量中找到方法名称的脚本中运行方法?

Is it possible to run a method in a script where the method's name is found from a text variable?

例如:

public text MyVariable;

public void Start()
{
    MyVariable = RunMeBaby;
    MyVariable();
} 

public void RunMeBaby()
{
    Debug.Log("You did it!");
}


在上面的示例中,我将变量MyVariable"分配给RunMeBaby"(我要调用的方法的名称),然后尝试调用它.


In the above example I'm assigning the variable 'MyVariable' to 'RunMeBaby' (the name of the method I want to call) and then attempting to call it.

以上对我不起作用,但还有其他方法吗?

The above doesn't work for me, but is there another way?

编辑以在下面添加其他说明

EDIT TO ADD ADDITIONAL CLARIFICATION BELOW

我目前正在创建自己的纸牌游戏.我创建了一个可编写脚本的对象 (CardAsset) 来处理我所有填充的卡片都需要的一些字段.类似的东西:

I am currently creating my own card game. I've created a scriptable object (CardAsset) to handle some fields that all my populated cards will need. Stuff like:

卡片名称(字符串)

成本(整数)

图像(图像)

描述文本(字符串)

现在我的原型的所有其他东西都已经完成(比赛场地、套牌等),我需要开始为我的卡片实际制作效果.由于每张牌都不同,但有些效果是相同的(例如,抽更多牌并对角色造成伤害很常见),我想我可以改变我的可脚本化对象 CardAsset 以包含一些脚本和变量:

I'm now at the point all the other stuff for my prototype is complete (playing field, deck, etc), and I need to start actually making the effects for my cards. Since every card is different but some of the effects are the same (draw more cards and deal damage to a character are very common for instance), I figured I could alter my scriptable object CardAsset to include some scripts and variables:

卡片名称(字符串)

成本(整数)

图像(图像)

描述文本(字符串)

Effect1(脚本)

Effect1 (script)

Effect1Amount (int)

Effect1Amount (int)

Effect2(脚本)

Effect2 (script)

Effect2Amount (int)

Effect2Amount (int)

Effect3(脚本)

Effect3 (script)

Effect3Amount (int)

Effect3Amount (int)

通过这种方式,我可以创建最多对它们具有 3 个效果的 CardAssets(再次例如对角色造成伤害或绘制卡片),然后在我的游戏中使用某些东西在玩家使用该卡片时使用相关变量调用这些脚本.

This way, I could create CardAssets with upto 3 effects on them (again such as dealing damage to a character or drawing cards) and then use something in my game to call those scripts with the associated variables when the player plays that card.

我的问题是我无法将脚本附加到我的 CardAsset,所以我认为一个合适的解决方法是在 CardAsset 上的 Effect1/Effect2/Effect3 插槽中输入方法的名称(DealDamage、DrawCards)(将它们更改为字符串),然后读取它们并在别处调用关联的方法.

My issue is that I cannot attach scripts to my CardAsset, so I figured a suitable workaround would be for me to type in the name of a method (DealDamage, DrawCards) in the Effect1/Effect2/Effect3 slot on the CardAsset (changing them to a string), and then have something read them and call the associated method elsewhere.

我知道此解决方案容易出错并且维护/更改可能会很痛苦,那么有没有更好的方法可以做到这一点?

I understand that this solution is prone to errors and could be painful to maintain/change, so is there a better way I could do it?

推荐答案

您好,欢迎来到 Stack Overflow,

Hello and welcome to Stack Overflow,

我不知道有关您的文本类的详细信息,但是根据您的问题,我假设它是一个字符串容器(可以这么说).您可以使用反射完全按照您的要求执行(根据字符串调用方法):

I don't know the details about your text class, but from your question I assume it's a string container (so to say). You can do exactly what you are asking (calling a method based on a string) using reflection:

// You need the class name, so I just called it MyClass
public class MyClass 
{
    public void Start()
    {
        string methodName = "RunMeBaby";

        // Invoke the method using reflection
        typeof(MyClass).GetMethod(methodName)?.Invoke(this, null);
    } 
...

然而,这是一个非常昂贵(并且容易出错)的调用.我的建议是使用不太通用的方法:

However this is a VERY expensive (and error prone) call. My suggestion would be to use a less versatile approach:

public void Start()
{
    // assuming text.Text is your string property
    string methodName = "RunMeBaby";
    
    CallMethod(methodName);
} 

private void CallMethod(string methodName)
{
    switch(methodName)
    {
        case nameof(RunMeBaby):
            RunMeBaby();
            break;
        case nameof(SomeOtherMethod):
            SomeOtherMethod();
            break;           
    }
}

private void RunMeBaby()
{

}

private void SomeOtherMethod()
{

}

注意:我不知道你从哪里得到你的方法字符串,但如果它不是来自某个外部来源(例如用户输入),最好建议你使用 nameof 关键字而不是硬编码字符串.如果可能,您应该完全摆脱这些字符串,并用表示可调用方法的枚举替换它们,例如,但此解决方案取决于您的用例.

NOTE: I don't know where you get your method strings from, but if it is not from some outer source (e.g. user input), you are best advised to use the nameof keyword instead of hard coded strings. If possible you should get rid of the strings altogether and replace them with an enum representing the callable methods for example, but this solution depends on your usecase.

这篇关于C# Unity2D 是否可以基于字符串调用脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆