猿问

将脚本放入数组?

我刚刚开始在 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 script

public ClicksPerSecondManager[] cps;


// Use this for initialization

void 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 initialization

void Start () {

    baseCost = cost;

  mainButton = GameObject.FindGameObjectWithTag("Player").GetComponent<MainButton>();


}


// Update is called once per frame

void 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());

    }

}


慕妹3242003
浏览 148回答 2
2回答

冉冉说

问题是cps = GameObject.FindGameObjectsWithTag("CPS"); 返回一个数组,GameObject所以当你使用 a 时,返回的ForEach每个对象都来自 TypeGameObject所以你不能只使用foreach(ClicksPerSecondManager item in cps)因为cps不包含一个数组ClicksPerSecondManager,它包含一个数组,GameObject所以你可以这样做foreach(GameObject item in cps){&nbsp; &nbsp; ClicksPerSecondManager cpsm = item.getComponent<ClicksPerSecondManager>();&nbsp;&nbsp; &nbsp; //now you have access to its public properties or methods&nbsp; &nbsp; Debug.log(cpsm.count);&nbsp; &nbsp; //etc}
随时随地看视频慕课网APP
我要回答