【问题标题】:Unity3D C# Script : Class Variable Array Data IssueUnity3D C# 脚本:类变量数组数据问题
【发布时间】:2016-10-30 05:04:03
【问题描述】:

我有一个简单的问题要问。只需检查下面的代码,问题就在代码的结果中。我希望你们能帮助我..

文件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# arrays class unity3d unityscript


【解决方案1】:

这是因为在 C# 中itema = database.items [0]; 不会创建副本,而是 itema 将始终指向对象。所以发生的事情是你没有向你的数组添加重复项,而是所有的东西都指向同一个元素,即database.items[0] 的值。这反过来又被修改了。

我宁愿建议你像这样创建一个新的类实例

在 items 中设置 database.items[0] 值

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

然后分配这个项目 tmp [0] = itema;

请记住,在 c# 中,变量只是指向对象,并且在您尝试分配它时不会创建重复项。你需要管理它。

【讨论】:

  • 嗨,killer_mach,我已按照您的建议使用 itema = new items(database.items [0].name, database.items [0].ID, ....) 但我收到如下错误:item' does not contain a constructor that takes 12' 参数类型。我已经在 item.cs 中有构造函数了。我该怎么办?
  • 在上面的问题中分享你的课程,我们可以看看
  • 我首先进入了你的旧编辑历史,你的班级有 13 个参数公共项目(字符串名称、int ID、字符串 desc、int Harvexx、int time、int stdpricex、int hightpricex、int stock, int Lvlunlockx, RawTree RawTree, ItemType type, ItemProd prod, string folder) { } 你怎么期望它有 12 个参数
  • 请查看错误。这是非常基础的编程。您只需要添加 13 个参数或创建另一个接受所需参数的构造函数。你只有 12 个
  • 我很高兴它成功了。如果您认为这可行,请将答案标记为解决方案。
猜你喜欢
  • 2011-06-05
  • 1970-01-01
  • 2016-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多