Unity3D C#脚本:类变量数组数据问题
我有一个简单的问题要问。 只需检查下面的代码,问题最终是代码的结果。 我希望你们能帮助我..
文件inventory.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
public class inventory : MonoBehaviour {
    public List<item> tmp = new List<item> ();
    public item itema;
    itemDatabase database;
    // Use this for initialization
    void Start () {
        int slotAmount = 0;
        database = GameObject.FindGameObjectWithTag ("itemDatabase").GetComponent<itemDatabase> ();
        //Generate the Slot and Slot Name;
        for(int i = 1; i <= 24; i++) {
                tmp.Add (new item());   
        }
        itema = database.items [0];
        tmp [0] = itema;
        tmp [0].itemStock = 1;
        Debug.Log (tmp[0].itemID + " - " + tmp[0].itemStock);
        itema = database.items [0];
        tmp [1] = itema;
        tmp [1].itemStock = 2;
        Debug.Log (tmp[1].itemID + " - " + tmp[1].itemStock);
        itema = database.items [0];
        tmp [2] = itema;
        tmp [2].itemStock = 3;
        Debug.Log (tmp[2].itemID + " - " + tmp[2].itemStock);
        Debug.Log (tmp[0].itemID + " - " + tmp[0].itemStock);
        Debug.Log (tmp[1].itemID + " - " + tmp[1].itemStock);
    }
}
结果是:
tmp Array [0] : 1 Stock 1
tmp Array [1] : 1 Stock 2
tmp Array [2] : 1 Stock 3
tmp Array [0] : 1 Stock 3 // this array recently stock was 1 now replace with 3 Why it is replace i have use an array ?
tmp Array [1] : 1 Stock 3 // this array recently stock was 2 now replace with 3 Why it is replace i have use an array ?
问题在tmp Array [0]和tmp Array [1]上被tmp Array [2]取代。
谢谢丹尼斯
  这是因为在C#中itema = database.items [0];  将不会创建副本,而是itema将始终指向对象。  所以发生的是你没有向你的数组添加重复项,而是所有的东西都指向了相同的元素,即database.items[0]的值。  反过来,它正在被修改。 
我宁愿建议你创建一个像这样的新类实例
在项目中设置database.items [0]值
 itema = new items( database.items [0].name, database.items [0].ID, ....) 
然后分配这个itema tmp [0] = itema;
记住,在c#中,变量只是指向对象,并且在尝试分配时不会创建重复。 你需要管理它。
链接地址: http://www.djcxy.com/p/52779.html