来自另一个脚本的Unity3D Access类

时间:2016-01-26 16:04:18

标签: unity3d binaryformatter

  

嘿我怎么能从另一个访问这个int和字符串列表   脚本?

 // Slot One Data
    [Serializable]
    public class SlotOneStats
    {
        public string nameOne;
        public int roleOne;
        public int strengthOne;
        public int meleeOne;
        public int shootingOne;
        public int huntingOne;
        public int cookingOne;
        public int craftingOne;
        public int buildingOne;
        public int engineeringOne;
    }
  

我尝试将'public'更改为'static'或'public static',但每当我改为静态时   它会说

     

静态成员`Main.SlotOneStats.ALLTHESTATICVARIABLEGOESHERE'无法访问   实例引用,使用类型名称来限定它

                        BinaryFormatter bfWriter = new BinaryFormatter();
                        FileStream file = File.Create(Application.persistentDataPath + "/dataStats" + onSlot + ".fgsv");

                        if(onSlot == 1)
                        {
                            SlotOneStats slotoneStats = new SlotOneStats();
                            slotoneStats.nameOne = name;
                            slotoneStats.roleOne = role;
                            slotoneStats.strengthOne = strength;
                            slotoneStats.meleeOne = melee;
                            slotoneStats.shootingOne = shooting;
                            slotoneStats.huntingOne = hunting;
                            slotoneStats.cookingOne = cooking;
                            slotoneStats.craftingOne = crafting;
                            slotoneStats.buildingOne = building;
                            slotoneStats.engineeringOne = engineering;

                            bfWriter.Serialize(file, slotoneStats);
                        }

1 个答案:

答案 0 :(得分:1)

我建议将该类的公共实例添加到第一个脚本中:

public class SlotOneStats
{
    public string nameOne;
    public int roleOne;
    public int strengthOne;
    public int meleeOne;
    public int shootingOne;
    public int huntingOne;
    public int cookingOne;
    public int craftingOne;
    public int buildingOne;
    public int engineeringOne;
}

public SlotOneStats SOS;

现在只需访问公共变量SOS,它应该有效:

GameObject example = GameObject.Find("Object_with_script").GetComponent<Script_with_class>.SOS;
// do stuff with example