首页 > 解决方案 > 如何在其他脚本中使用变量值作为变量名?

问题描述

我有一个带有配置文件的统一项目(用于动画名称)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public static class Anims{

public const string anim1= "NameOf anim1";
public const string anim2= "NameOf anim2";
public const string anim3= "NameOf anim3";
...
}
public enum animNames { anim1, anim2,anim3...}

在另一个脚本中,我想使用激活动画

public animNames name_Of_The_Anim_I_Want_To_Activate;

我的问题是转换name_Of_The_Anim_I_Want_To_Activate.ToString()成实际的动画名称

我可以使用哪个工具 name_Of_The_Anim_I_Want_To_Activate = anim1变成“NameOf anim1”;

我想通过枚举,因为有几个按钮每个触发另一个动画 1。我不想使用继承或多个脚本 2。我想尝试一种比 switch 语句更优雅的方式。这就是为什么我不能枚举能够到达变量名的原因。

编辑:最终我为单一行为管理器倾倒了“静态配置文件”的想法,然后我可以拥有(静态/常量或非)公共字符串 anim1=“name1”;公共字符串 anim2 = "name2";

public enum CompAnim
{
   Company1,
   Company2,
}

并使用

public string CompanyAnim(CompAnim comp)
{
    string toRun = 
    this.GetType().GetField(comp.ToString()).GetValue(this).ToString();
    return toRun;
}

感谢 Camile 提供的优雅解决方案,这正是我想要的。

标签: c#unity3dconstants

解决方案


假设在 Anims 中你有:

public string anim1 = "someAnimation";

在存储实际动画的脚本中:

public string someAnimation = "theActualAnimationName";

...

string toRun = this.GetType().GetField(someAnimNamesEnumValue.ToString()).GetValue(this);

这会将“theActualAnimationName”分配给变量toRun

如果您将动画存储为 Animation 对象而不是字符串,您也可以通过上述方法直接使用它们。

编辑: 另外你可能想看看反射是什么(这就是代码正在做的事情)


推荐阅读