我刚刚开始在 Unity 中编程,但还不太擅长。我正在尝试制作一个简单的 cookie clicker 游戏并且正在观看本教程,并且在 18:34 左右他写下了一些代码,如下所示。我认为他的代码已经过时,Unity 无法像以前那样工作(不过我不确定)。他的密码public Text Gps;public Click click;public ItemManager[] items;public int getGoldPerSecond(){ int tick=0; foreach(ItemManager item in items) { tick +=item.count * item.tickvalue; }}我的代码:public Text LPS;public MainButton mb; //same as his Click click scriptpublic ClicksPerSecondManager[] cps;// Use this for initializationvoid Start () { cps = GameObject.FindGameObjectsWithTag("CPS");}public int getLikesPerSecond(){ int tick = 0; foreach(ClicksPerSecondManager item in cps) { tick += cps.count * cps.LikesPersecond; } return tick;}我知道代码无法访问变量或其他东西。有人请向我解释如何将对象存储到数组中。这里发生的事情是我有一家商店,里面有 3 件商品。这是附加到 3 个项目的脚本public Text itemDesc;MainButton mainButton;public float cost;public int LikesPerSecond;public int count;public string itemName;private float baseCost;public GameObject sucessfulPurchase;public GameObject failedPurchase;public Image Panel;// Use this for initializationvoid Start () { baseCost = cost; mainButton = GameObject.FindGameObjectWithTag("Player").GetComponent<MainButton>();}// Update is called once per framevoid Update () { itemDesc.text =itemName+ "\nCost : "+cost+"\nLPS : "+LikesPerSecond ;}public void purchasedItem(){ if (mainButton.noOfLikes >= this.cost) { mainButton.noOfLikes -= cost; //minus away cost count += 1; cost = Mathf.Round(baseCost * Mathf.Pow(1.15f, count)); sucessfulPurchase.gameObject.SetActive(true); StartCoroutine(WaitFor1Second()); } else if (mainButton.noOfLikes < cost) { failedPurchase.gameObject.SetActive(true); StartCoroutine(WaitFor1Second()); }}
2 回答
冉冉说
TA贡献1877条经验 获得超1个赞
问题是cps = GameObject.FindGameObjectsWithTag("CPS"); 返回一个数组,GameObject所以当你使用 a 时,返回的ForEach每个对象都来自 TypeGameObject所以你不能只使用foreach(ClicksPerSecondManager item in cps)因为cps不包含一个数组ClicksPerSecondManager,它包含一个数组,GameObject所以你可以这样做
foreach(GameObject item in cps){
ClicksPerSecondManager cpsm = item.getComponent<ClicksPerSecondManager>();
//now you have access to its public properties or methods
Debug.log(cpsm.count);
//etc
}
- 2 回答
- 0 关注
- 147 浏览
添加回答
举报
0/150
提交
取消