Array.Indexof混乱

时间:2017-08-04 00:38:14

标签: c# unity3d

Hellos家伙我是初学者,有2个班级。 A类有一个我需要在B组中访问的数组。我在这里搜索过去36个小时尝试不同的方法,这是我最后得到的帮助吗?

这是第一个带有数组的类

[System.Serializable]
public class Cli
{
    public string name;
    public int money;
};

public class BankManager : MonoBehaviour
{
    private static BankManager _instance;

    public static BankManager Instance
    {
        get
        {
            if (_instance == null)
            {
                GameObject go = new GameObject("BankManager");
                go.AddComponent<BankManager>();
            }
            return _instance;
        }
    }

    public GameObject player;
    private string NaMe;
    public Bank[] banks = new Bank[1];
    public Cli[] clients = new Cli[1];

    void Awake()
    {
        _instance = this;
    }

    void Start()
    {
        banks[0] = new Bank("In But Not Out", 10000);
        player = GameObject.Find("Player");
        clients[0].money = 1000;
    }

    void Update()
    {
        PlayerController pName = player.GetComponent<PlayerController>();
        clients[0].name = pName.name;

    }
}

我尝试访问的数组是客户端[]

public class AccessAtm : MonoBehaviour
{
    public Bank bank;
    public int clams;

    private void OnTriggerEnter2D(Collider2D other)
    {
        bank = BankManager.Instance.banks[0];
        if (other.tag == "Player")
        {
            clams = Array.IndexOf(BankManager.Instance.clients, 
                other.GetComponent<PlayerController>().name);
            Debug.Log(other.GetComponent<PlayerController>().name);
        }
    }
}

debug.log正确地告诉我我得到了player.name我相信我的错误是获取该数组的实例或者在indexof命令中

1 个答案:

答案 0 :(得分:0)

问题是IndexOf希望您为第二个参数传递Bank的实例

clams = Array.IndexOf(BankManager.Instance.clients, 
            other.GetComponent<PlayerController>().name);

你传给它一个字符串。

您需要使用其他内容来搜索它,而更简单的解决方案是使用for循环。

var clients = BankManager.Instance.clients;
var otherName = other.GetComponent<PlayerController>().name;
int foundAt = -1;
for(int i = 0; i < clients.Length; i++)
{
    if(clients[i].name == otherName)
    {
        foundAt = i;
        break;
    }
}
claims = foundAt;