【问题标题】:Adding new variables to variable array向变量数组添加新变量
【发布时间】:2012-03-28 13:40:53
【问题描述】:

我有这个成分数组,其中包含多个变量(如名称、图标、值等)。当玩家超过某些点时,必须将新成分添加到该成分数组中。所以我有另一个数组,其中包含新成分的图标和名称(值将在运行时单独添加)。

但问题是您不能使用 Add 向成分数组添加新元素(也尝试为两个数组提供相同的变量),或者只是在最后添加一个新元素并分别填充元素。

成分解锁脚本:

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

public class progressManager : MonoBehaviour {
    
    private int ingUnlockLevel;
    private int lockLevel = 0;
    private int newIngScore = 500;
    public List<ingUnlocks> ingUnlock = new List<ingUnlocks>();
    public List<GameObject> lockedCraft = new List<GameObject>();
    public Texture locks;
    public Texture normal;
    private bool upGrade;
    
    public TextMesh nextIngredient;
    // Update is called once per frame
    void Update () {
        
        nextIngredient.text = ingUnlock[lockLevel].name;
        
        ingUnlockLevel = GetComponent<gameMechanics>().headScore;
        
        if(ingUnlockLevel >= newIngScore){upGrade = true;}
        
        if(upGrade == true){    
            GetComponent<productManager>().ingredient.;
            newIngScore = newIngScore *2;
            lockLevel+=1; 
            upGrade = false;
        }
    }
    
    [System.Serializable]
    public class ingUnlocks{
        public string name;
        public Texture icon;
    }
}

以及玩家成分的部分脚本:

using UnityEngine;
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;

public class productManager : MonoBehaviour {

    private class ingredientComparer : IComparer<ingredients>{
        
        public int Compare(ingredients a, ingredients b)
        {
            return ((int) a.c2cPerc ) - ((int) b.c2cPerc);
        }
    }

        public List<ingredients> ingredient = new List<ingredients>();
}

[System.Serializable]
public class ingredients{
    
    public string name;
    public Texture icon;
    public int score;
    public int quantity;
    public float c2cPerc;
    public bool usable;
    
}

有什么方法可以将解锁数组中的新名称和图标添加到玩家成分数组中?

【问题讨论】:

  • "但问题是您不能使用 Add 向成分数组添加新元素(也尝试为两个数组提供相同的变量),或者只是在末尾添加一个新元素分别填充元素。”为什么不呢?
  • 数组是不可变的,如果你想要一个增长的数据结构,使用列表。
  • 所以,你是说ingUnlock.Add(new ingUnlocks()); 不起作用
  • @MrFox 但示例代码显示的是列表,而不是数组。凯文,您的示例代码没有声明单个数组。因此,我对您的问题感到困惑。

标签: c# arrays variables unity3d


【解决方案1】:

很难说你到底在追求什么,但这能回答你的问题吗?:

GetComponent<productManager>().ingredient.Add(new ingredients { name = ingUnlock[locklevel].name, icon = ingUnlock[locklevel].icon });

PS:我刚刚完成了您示例中无法编译的代码行,并在那里添加了一个新的成分项,猜想这就是您想要做的。

【讨论】:

  • 是的!这就像一个魅力。我不知道如何向变量数组添加多个引用,但现在我知道了!太感谢了!谢谢大家的帮助和cmets。
猜你喜欢
  • 2022-10-05
  • 2023-03-29
  • 1970-01-01
  • 1970-01-01
  • 2019-01-22
  • 1970-01-01
  • 1970-01-01
  • 2020-09-10
相关资源
最近更新 更多