2016-09-12 48 views
0

我有一个涉及2个不同脚本的问题。我试图实现的是使用字符串来访问像标题​​所示的静态变量。对静态变量使用字符串?

我的第一个剧本:

using UnityEngine; 
using System.Collections; 

public class GameInformation : MonoBehaviour 
{ 
    //Upgrades Info, 1 is bought while 0 is not bought 
    public static int TipJar; 
} 

我的第二个脚本:

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

public class Upgrades : MonoBehaviour 
{ 

public List<PlayerTank> playerList; 
public class PlayerTank // Here is my class for PlayerTank 
{ 

    public string Name; 
    public string Value; 

    // This is a constructor to make an instance of my class. 
    public PlayerTank (string NewName, int NewValue) 
    { 
     Name = NewName; 
     Value = NewValue; 
    } 
} 

void Start() 
{ 

    playerList = new List<PlayerTank>(); 

    playerList.Add (new PlayerTank("TipJar", GameInformation.TipJar)); 

    //To loop all the list 
    for(int i = 0; i < playerList.Count; i++) 
    { 
     int TempInt = i; 

     playerList[i].NewValue += 1; //This line works but Gameinformation.TipJar will still contain the value 0, i want it to be 1. 

    } 
} 

} 

我的目标是更新GameInformation.TipJar值,但它一直含0

我试图用GameInformation.playerList[i].Name(which is TipJar) += 1替换playerList[i].NewValue += 1;

我一直在寻找一段时间,我找不到解决方案,任何想法?

+1

这个问题不是很清楚,你想达到什么目的?你有预期的产量吗? – Bassie

+0

对不起,你想达到什么目的?很不清楚 – Tinwor

+0

你的GameInformation类只定义了一个int var“TipJar” – joreldraw

回答

0

,我的目标就是使GameInformation.TipJar的值为1时,内部的for循环();

以从你这个评论,我认为GameInformation.TipJar意味着是全球性的(这意味着它应该是1在循环的时候,不管playerList的内容)。我会为您提供此假设下,解决你的问题有2种方法:

1.使用静态变量(简单的方法)

如果这是正确的,那么就设置静态像GameInformation.TipJar = 1;权利之前循环开始,然后在循环之后立即设置它GameInformation.TipJar = 0;

2.使用反射

如果你有你的GameInformation对象的引用(假设它被命名为gio),你可以通过现场的名字作为一个字符串设置其字段:gio.GetType().GetField("TipJar").SetValue(gio, value)。 (参见:https://msdn.microsoft.com/en-us/library/6z33zd7h(v=vs.110).aspx


如果不回答你的问题,那么我很抱歉,我真的不明白你正在尝试做的。

+0

啊谢谢你帮助我很多:) – OddTuna

1

最有可能是一个错字?

变化

GameInformation.playerList[i].Name += 1; //This line will not work 

playerList[i].Name += 1; 

而且现场NameString型的,所以我怀疑+1有道理这里。我想你想对不起,我不清楚的问题类似

playerList[i].Name += (i + 1);