【问题标题】:access an array in another script with variable name?使用变量名访问另一个脚本中的数组?
【发布时间】:2014-12-12 13:14:26
【问题描述】:

我是编程新手,我需要帮助来解决出现的问题。 我试图在另一个脚本中访问一个数组,通常没有问题。但我的情况是这样的:

例如:

脚本 A 包含几个具有不同非数字名称的数组。

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

   public class ScriptA : MonoBehaviour {
   public int[] keys = new int[4];
   public int[] screws= new int[4];
   public int[] nails= new int[4];
   public int[] iron= new int[4];
   ....
   }

现在在脚本 B 中,我需要访问这些数组,但需要使用一个变量。我该怎么做?

例如:

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

public class ScriptB: MonoBehaviour {
    ScriptA scriptA;
    public string arrayName;    // Here user could type in the name of an array



    void Start()
    {
        scriptA = GameObject.Find("Object").GetComponent<ScriptA>();

        // This try to access the array of course not works. But how?
        scriptA.arrayname;   
    }

感谢您的想法和解决方案。我认为这不是一个难题,但我不知道如何解决它。

【问题讨论】:

  • 如果您想访问例如keys,您可以使用scriptA.keys 或单个元素scriptA.keys[0]
  • 是的,我知道,但我需要使用 ScriptB 中的字符串变量“arrayName”访问数组

标签: c# arrays variables unity3d


【解决方案1】:

你要么需要反射(丑陋),要么你可以在ScriptA中定义一个Dictionary&lt;string, int[]&gt;,像这样:

public class ScriptA : MonoBehaviour
{
    public int[] keys = new int[4];
    public int[] screws = new int[4];
    public int[] nails = new int[4];
    public int[] iron = new int[4];
    public Dictionary<string, int[]> arrays;

    void Start()
    {
        arrays = new Dictionary<string, int[]>
        {
            { "keys", keys },
            { "screws", screws },
            { "nails", nails },
            { "iron", iron }
        };
    }
}

然后你在ScriptB 中使用它,如下所示:scriptA.arrays[arrayName]

【讨论】:

  • 这就是我要找的。非常感谢:)
  • 数组是否需要静态才能在字典中实现?这不会很好。
  • 据我所知,它们不需要是静态的。您是否遇到编译器错误?
  • 是的。使用下面的代码,我得到了这个错误:“字段初始化程序无法引用非静态字段、方法或属性 'ScriptA.keys'”。如果我将键数组更改为静态,它可以正常工作,但我不希望这个数组是静态的。
  • 现在它使用Start 方法来创建字典。
【解决方案2】:

我知道这不是你想要的,但你想要做的(根据我的推断)是让编译器让你向未知类型的类添加动态属性。据我所知,C# 这是不可能的。您可以做些什么来解决这个问题,您基本上可以在所谓的 ScriptA 中有一个方法,该方法将接受具有以下内部功能之一的字符串参数

 public object GetPropertyValue(string propName){
     switch (propName){
        case: "keys"
          //do whatever you need to do with keys
        //and so on
     }
 }

答:如果你将这些字段封装在属性中,那么

 public object GetPropertyValue(string propName){
      System.Reflection.PropertyInfo pi= (typeof(ScriptA)).GetProperty(propName);
      pi.GetValue(this,null);
 }

B:如果你不想封装它们,那么

 public object GetFieldValue(string fieldName){
      System.Reflection.FieldInfo fi= (typeof(ScriptA)).GetField(fieldName);
      fi.GetValue(this,null);
 }

在 MSDN 上阅读有关 PropertyInfoFieldInfo 的更多信息。

【讨论】:

  • 不是keysscrewsnailsiron 字段,而不是属性? PropertyInfo 也适用于这些吗?
  • 嗯,是的,真的。不知怎的,我忘记了这一点。谢谢我编辑了这个问题。但无论如何,C# 中的约定是不将字段公开,而是将它们私有化,并让其他人通过属性访问它们。
  • Unity(这个问题使用的)似乎没有遵循所有 C# 约定。
猜你喜欢
  • 2013-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-16
  • 1970-01-01
  • 2018-01-19
  • 1970-01-01
相关资源
最近更新 更多