我在 c# 中有一個 Unity 腳本,其中宣告了一個公共的精靈串列,然后在檢查器中手動填充。
該串列由 19 個汽車精靈組成。
這些汽車只有在玩家完成每個級別時才可用。
例如:當你第一次打開游戲時,你只有一輛可用的汽車,但如果你完成了第 1 關,你會解鎖另一輛車,當你完成第 2 關時,你會得到另一輛車,依此類推。
我的問題是,由于我手動填充了串列,當關卡完成后,如何重新添加相同的精靈?
我打算用來cars.RemoveRange(1, 18)從串列中洗掉它們,但不知道如何在不手動呼叫每個精靈的情況下將它們添加回來。我相信有一種我不知道的更簡單、更好的方法。
這是腳本:
public class CarSelection : MonoBehaviour
{
public List<Sprite> cars; //store all your images in here at design time
public Image displayImage; //The current image thats visible
public Button nextCar; //Button to view next image
public Button previousCar; //Button to view previous image
private int i = 0; //Will control where in the array you are
void OnEnable()
{
//Register Button Events
nextCar.onClick.AddListener(() => NextCarButton());
previousCar.onClick.AddListener(() => PreviousCarButton());
}
private void Start()
{
cars.RemoveRange(1, 18);
if (FinishLineTouch.levelOneComplete == true) {
//Re-adding the same sprites here
}
}
public void NextCarButton()
{
if (i 1 < cars.Count)
{
i ;
}
}
public void PreviousCarButton()
{
if (i - 1 >= 0)
{
i--;
}
}
void Update()
{
if (LevelSelect.isCarChosen == true) {
nextCar.interactable = false;
previousCar.interactable = false;
}
displayImage.sprite = cars[i];
}
}
提前致謝。
uj5u.com熱心網友回復:
您的邏輯在這里有一個小缺陷。假設您在檢查器中添加汽車精靈,洗掉所有精靈并不理想。
您可以擁有所有精靈的串列,以及帶有可用選項的串列(以 sprite[0] 開頭并在每次完成關卡時添加)。
但是,如果您想知道如何在洗掉它們后重新添加它們,則需要在全域變數中進行復制,因此嘗試我上面的建議會更有效。
uj5u.com熱心網友回復:
你應該有兩個不同的陣列,一個用于精靈,另一個用于玩家解鎖它的情況。或者您應該創建一個具有汽車精靈的自定義類,如果它尚未解鎖。
uj5u.com熱心網友回復:
聽起來你真正需要做的就是確保索引不超過解鎖的汽車
if(i 1 < cars.Count && i 1 <= amountOfFinishedLevels)
{
i ;
// and then you really should do this in both methods and not every frame
displayImage.sprite = cars[i];
}
并且根本不要洗掉/閱讀任何專案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/410960.html
標籤:
上一篇:Javascript-為什么函式只在最后一次呼叫時起作用?
下一篇:如何使回圈作業而不不斷增加索引?
