我有一个简单的问题。
我有两个文件脚本:Player.cs
using UnityEngine; using System.Collections; using System.Collections.Generic; public class player { public List<item> itemx = new List<item> (); // Here }
文件Inventory.cs using UnityEngine; using System.Collections; using System.Collections.Generic; using UnityEngine.UI; public class inventory : MonoBehaviour { public player playerx; itemDatabase database; // Use this for initialization void Start () { database = GameObject.FindGameObjectWithTag ("itemDatabase").GetComponent<itemDatabase> (); //Generate the Slot and Slot Name; for(int i = 1; i <= 24; i++) { playerx.itemx.Add(new item()); // Here playerx.itemx[i] = database.items[i]; // And Here } } }
你可以在player.cs文件中看到,我声明了一个列表变量:
public List<item> itemx = new List<item> (); // Here
和在Inventory.cs文件我想添加的值使用:
playerx.itemx.Add(new item()); And Here
是否可以将value变量保存到player.cs文件?
谢谢
说明
在你的问题中,你有 public class Player
不是 public class Player:MonoBehaviour
我想这只是一个打字错误。如果你想享受"免费"类Player(如在OO环境中),您不能这样做。
正确,这样做绝对没有问题!
注意,在第二个脚本中,它将是:
public player playerx; ... WRONG
public Player player; ... CORRECT
然后是
player.items.Add( .. etc )
(不要忘记,当然你必须通过拖动来连接播放器&;Player &;检查变量。如果你不知道怎么做,告诉我,我会给你一个教程的链接。
第二,在第一个脚本中你有一个问题。
Unity中有个愚蠢的东西"public"意思是"检查器变量"
实际上你想要一个"普通的"。公共变量和任何普通编程语言一样,奇怪的是你必须输入这个
<标题>"系统。NonSerialized] public"这只是Unity的奇怪之处之一。事实上,在许多项目中,您从不使用检查器变量。所以你只是不断地输入"[系统。NonSerialized] public"无处不在。长一个[系统]。NonSerialized] public"是一种"正常"一个,如果你明白我的意思。一直使用它。只有当你特别需要一个检查器变量时,才可以使用"public"
public List<item> itemx... WRONG
[System.NonSerialized] public List<item> items... CORRECT
标题>这个怎么样?假设数据库对象返回[items]或其他。
database = GameObject.FindGameObjectWithTag
("itemDatabase").GetComponent<itemDatabase> ();
//Generate the Slot and Slot Name;
forach(item _item in database.items)
{
playerx.itemx.add(_item);
}
如果你的数据库返回不同的东西,你可以尝试
playerx.itemx.add(new item
{
itemproperty1 = _item.property1,
and so on.
};