首页 > 解决方案 > 如何用字符串数组初始化一个类?

问题描述

我有这个脚本,它通过着色器的名称获取属性:在底部,我通过提供属性名称来更改其中一个属性值:“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 属性创建这个脚本来创建一个编辑器脚本,仅用于获取属性,然后像我给出的示例一样使用这个单声道脚本中的属性。

标签: c#unity3d

解决方案


只是你的标题:你有一个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];

推荐阅读