c# - 如何在其他脚本中使用变量值作为变量名?
问题描述
我有一个带有配置文件的统一项目(用于动画名称)
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 提供的优雅解决方案,这正是我想要的。
解决方案
假设在 Anims 中你有:
public string anim1 = "someAnimation";
在存储实际动画的脚本中:
public string someAnimation = "theActualAnimationName";
...
string toRun = this.GetType().GetField(someAnimNamesEnumValue.ToString()).GetValue(this);
这会将“theActualAnimationName”分配给变量toRun
如果您将动画存储为 Animation 对象而不是字符串,您也可以通过上述方法直接使用它们。
推荐阅读
- python-3.x - PyQt5如何多个QRunnable报告进度和最终结果
- javascript - 如何将这些多个功能链接在一起?
- c++ - 公开一个类内部的私有 std::bitset 字段以进行修改
- assembly - 有没有办法为小数乘法编写单指令?
- angular - 来自 Windows 的 http://localhost:4200 正在使用来自 WSL2 的 ng serve,怎么会?
- python-3.x - 如何通过 netmiko 或其他方式将渲染的 cisco 配置解析到大型网络设备
- css - 背景图像更改为外部图像链接不起作用
- javascript - 将外部 JS & CSS 转换为 HTML
- html - 如何从 Powershell 中的 ConvertTo-HTML -property 命令的输出中删除文本?
- gitlab - 继承 Gitlab 预定义的变量