c# - 如何用字符串数组初始化一个类?
问题描述
我有这个脚本,它通过着色器的名称获取属性:在底部,我通过提供属性名称来更改其中一个属性值:“Vector1_570450D5”
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.PlayerLoop;
public class ChangeShaders : MonoBehaviour
{
public Material material;
public float duration = 1;
private List<string> propertiesNames = new List<string>();
private void Awake()
{
material = GetComponent<Renderer>().material;
var propertiesCount = ShaderUtil.GetPropertyCount(material.shader);
for(int i = 0; i < propertiesCount; i++)
{
propertiesNames.Add(ShaderUtil.GetPropertyName(material.shader, i));
}
}
void Update()
{
var currentValue = Mathf.Lerp(-1, 1, Mathf.PingPong(Time.time / duration, 1));
material.SetFloat("Vector1_570450D5", currentValue);
}
}
但改为手动输入属性名称,我想为每个属性名称创建一个类,这样我就可以在 SetFloat 中输入类似的内容:
material.SetFloat(myProperties.Vector1_570450D5, currentValue);
在这种情况下,有 5 个属性,所以我希望能够做到:
material.SetFloat(myProperties.Vector1_570450D5, currentValue);
或者
material.SetFloat(myProperties.Color_50147CDB, currentValue);
所以我想用 executeallways 属性创建这个脚本来创建一个编辑器脚本,仅用于获取属性,然后像我给出的示例一样使用这个单声道脚本中的属性。
解决方案
只是你的标题:你有一个List<string>
,而不是一个数组;)
在用值填充它之前,您需要对其进行初始化。您也可以与字段声明一起执行此操作:
public List<string> names = new List<string>();
更简单的将是一个适当的构造函数,例如使用
public class MyClass
{
public List<string> names = new List<string>();
public MyClass(List<string> initialNames)
{
// This creates a new List<string> copying all elements of initialNames
names = new List<string>(initialNames);
}
}
然后像这样使用它
var myClass = new MyClass(names);
如果我理解正确,您正在进一步寻找像这样的财产
public string this[int index] => names[i];
这将允许您直接通过
myClass[i];
代替
myClass.names[i];
推荐阅读
- rollup - 将 lit-element 和 lit-html 添加到全局变量
- c# -
没想到。- XML 文档中存在错误 (2, 2) - javascript - 合并两个类 div
- python - 将文件保存到带有特殊字符的位置
- amp-html - 使用 Google Optimize 进行 AMP 重定向测试
- linux - 从makefile中的bash命令输出创建变量
- git - 能够推送和拉取多个 github 电子邮件/帐户,权限被拒绝(公钥,键盘交互)
- php - 如何在 PHP 中延迟 2 秒以包含?
- javascript - 为什么我的 js 对象不输出我放入其中的图像
- spring-boot - prometheus.yml 中指定的 Prometheus 目标中的端点 IP 未更改