如何通过在Unity中通过名称查找类型来将类型传递给方法。

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

How to pass a type to a method, by finding the type by its name in Unity

问题

Here is the translated code portion you requested:

我有一个方法,它会检查当前的游戏状态,并返回一个布尔值,以确定传入的值是否等于当前状态:

public bool IsEqualToCurrentState<T>() where T : GameState
{
    if (currentGameState is T)
        return true;

    return false;
}
我有多个游戏状态,其中一些是:`PointTutorialState, GrabTutorialState, MoveTruckState`...

通常情况下,我会这样调用该方法:

GameStateManager.Instance.IsEqualToCurrentState<PointTutorialState>()
现在,我正在编写一个脚本,该脚本将用于多个`gameObjects`,如果状态与`gameObject`负责的状态相同,则应突出显示该对象。因此,唯一的区别是该对象的状态类型。

我的想法是创建一个SerializeField字符串,其中存储了该对象的类型名称,并调用方法`IsEqualToCurrentState<>()`。

我尝试在Google中搜索,但没有找到我所需要的内容。ChatGPT也不能帮助我,但这是它写的内容:

```csharp
private bool MatchesTheGameState()
{
    Type newType = Type.GetType(nameState);
    MethodInfo method = typeof(GameStateManager).GetMethod("IsEqualToCurrentState");
    MethodInfo genericMethod = method.MakeGenericMethod(newType);
    return (bool)genericMethod.Invoke(GameStateManager.Instance, null);
}

接受nameState是这行代码:

[SerializeField] string nameState;

带有值:PointTutorialState

有没有解决方案,可以通过只提供所需状态的名称并将其转换为该类型以便传递来调用IsEqualToCurrentState方法?


Please note that the code has been translated, but it may not be executable in its current form as it contains HTML-encoded characters like `&lt;` and `&quot;`. You will need to replace these with the appropriate symbols ('<' and '"') in your code.

<details>
<summary>英文:</summary>

I have a method which checks the current game state and returns boolean if the passed value is equal to the current one:
    public bool IsEqualToCurrentState&lt;T&gt;() where T : GameState
    {
        if (currentGameState is T)
            return true;

        return false;
    }

I have multiple gamestates, a few of them being: `PointTutorialState, GrabTutorialState, MoveTruckState`...

Normally I would call the method this way:

GameStateManager.Instance.IsEqualToCurrentState<PointTutorialState>()



Now, I am writing a script which would be used on multiple `gameObjects` and should highlight the object if the state is the one that the `gameObject` is responsible for. So, the only difference is the type of the state for that object. 

My ideas was to make a serializeField string, where the name of the type for that object would be stored and call the method `IsEqualToCurrentState&lt;&gt;()`

I tried searching in google but I had no luck in finding what I needed. ChatGPT also couldn&#39;t help me, but this is what it wrote:
private bool MatchesTheGameState()
{
    Type newType = Type.GetType(nameState);
    MethodInfo method = typeof(GameStateManager).GetMethod(&quot;IsEqualToCurrentState&quot;);
    MethodInfo genericMethod = method.MakeGenericMethod(newType);
    return (bool)genericMethod.Invoke(GameStateManager.Instance, null);
}
accepting that nameState is this line of code:
[SerializeField] string nameState;
with value: PointTutorialState

Any solutions how I can call the IsEqualToCurrentState method by just giving the name of the desired state and converting it to that type so I can pass it?

</details>


# 答案1
**得分**: 1

你可以简单比较类型名称,这基本就足够了。

```csharp
public bool IsEqualToCurrentState(string stateName)
    => currentGameState?.GetType().Name == stateName;
英文:

You can simply compare the type name, this is basically enough.

public bool IsEqualToCurrentState(string stateName)
    =&gt; currentGameState?.GetType().Name == stateName;

答案2

得分: 1

这似乎是在你的Update()方法中有许多if语句,可能会变得复杂和有错误。

事件将使此过程更加简单和清晰,可在此处找到一个可工作的示例:https://www.youtube.com/watch?v=k4JlFxPcqlg

在需要将状态更改为PointTutorialState的地方调用OnPointTutorialState,然后在任何需要为该事件进行更改的对象中,添加一个事件处理程序,以进行所需的更改。根据对象和您的状态需求,您可能还需要一个OnPointTutorialStateExit事件。

最后,当完成教程时,可以清除所有教程状态/事件侦听器,以使事情变得更加清晰。

英文:

This sounds like a bunch of if statements in your Update() methods that could get complicated and buggy.

Events would make this easier and cleaner, a working example at: https://www.youtube.com/watch?v=k4JlFxPcqlg

You call OnPointTutorialState in the place where you would set the state to PointTutorialState, and then in any object that needs to change for that state change, add an event handler that makes the changes you need for that event. Depending on the object and your state needs, you might also need an OnPointTutorialStateExit event.

Finally, this could clean things up a bit in that when you are done with tutorials, you could disable all the tutorial state/event listeners.

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

发表评论

匿名网友

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

确定