将GameObjects的变量存储到Array [Unity]

时间:2016-04-12 06:45:53

标签: arrays unity3d gameobject

我有3种GameObject,分别是blueBook,redBook和greenBook。现场有2台blueBook,7台redBook和4台greenBook。

它们每个都分配有以下具有3个属性的示例脚本。

public class blueBook : MonoBehaviour {

    public string type = "BlueBook";
    public string colour = "Blue";
    public float weight;
    float s;

    void Start () {
        float weightValue;
        weightValue = Random.value;
        weight = Mathf.RoundToInt (700*weightValue+300);
        s=weight/1000; //s is scale ratio 
        transform.localScale += new Vector3(s,s,s);
    }

    // Update is called once per frame
    void Update () {
    }
}

在新类中,我想获取GameObject的所有变量(类型,颜色,重量)并将它们存储在数组中。怎么做?

将它们全部存储在数组中后,用户将输入权重。然后另一个类将搜索所有信息以删除具有相同重量的数组和GameObject(在场景中)。

谢谢。

更新

blueBook.cs

public class blueBook: MonoBehaviour {

public string type = "blueBook";
public string colour = "Red";
public float weight;
float s;

void Start () {
    float weightValue;
    weightValue = Random.value;
    weight = Mathf.RoundToInt (500*weightValue+100);
    s=weight/1000; //s is scale ratio 
    transform.localScale += new Vector3(s,s,s);
    Debug.Log(weight);
}

// Update is called once per frame
void Update () {
}

}

block.cs

public class block: MonoBehaviour{

public List<GameObject> players;

    void Start()
    {   Debug.Log(players[1].GetComponent<blueBoook>().weight);
    }

    // Update is called once per frame
    void Update () {

    }

block.cs的debug.log每次都显示为0,否则显示在bluebook.cs的debug.log中。这是因为它显示了初始数字?我不知道扫管笏是错的

1 个答案:

答案 0 :(得分:1)

对于一个列表中的所有块,您可以创建一个包含公共列表的脚本,并将所有游戏对象拖到检查器的列表中。

using System.Collections.Generic;

public class ObjectHolder : MonoBehaviour
{
    public List<GameObject> theBooks;

    // You can remove by weight e.g. like this
    public void DeleteByWeight(float inputWeight)
    {
        for(int i = theBooks.Count - 1; i >= 0; i--)
        {
            if(theBooks[i].GetComponent<Book>().weight == inputWeight)
                Destroy(theBooks[i]);
                theBooks.RemoveAt(i);
            }
        }
    }
}

需要将块上的脚本重命名为所有({我在示例中为Book)的名称。从您的代码中没有问题,因为它们只是成员的价值不同。