Unity3D C# Script : Class Variable Array Data Issue

I got a simple question to ask. Just Check below code and the question is in the end at the result of code. I hope you guys can help me..

file 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);


    }



}

and the result was :

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 ?

The Question is on tmp Array[0] and tmp Array[1] it was replace by tmp Array[2].

THanks Dennis


That is because in C# itema = database.items [0]; will not create a copy but rather itema will always point to object. So what is happening is you are not adding duplicates to your array but rather all the things point to same element that is the value of database.items[0] . Which in turn is getting modified.

I would rather suggest you to create a new class instance like this

Set database.items[0] values in items

itema = new items( database.items [0].name, database.items [0].ID, ....)

then assign this itema tmp [0] = itema;

remember in c# the varibles just point to the object and will not create duplicate when you try to assign it. You will need to manage that.

链接地址: http://www.djcxy.com/p/52780.html

上一篇: 动作委托使用在foreach循环之外声明的最后一个变量值

下一篇: Unity3D C#脚本:类变量数组数据问题