2016-10-09 19 views
1

在我基於Unity的Android遊戲中,我希望根據每個級別的問題數量動態添加圖像。圖像僅供參考。每個正確的答案將以綠色標出,而錯誤的答案則以紅色標出。我是團結一致的新手,並努力尋找實現這一目標的步驟。在運行時動態添加圖像 - Unity 5

任何有關此要求示例的幫助都將非常有幫助。

enter image description here

回答

1

我曾經寫了一個腳本,用於動態創建基於每個級別上的按鈕。我所做的是在場景中創建第一個按鈕,並根據第一個按鈕添加其他按鈕。下面是我的代碼的外殼:

// tutorialButton and levelButtons are public variables which can be set from Inspector 
RectTransform rect = tutorialButton.GetComponent<RectTransform>(); 

for (int i = 1; i < levelSize; i++) { 
    // Instantiate the button dynamically 
    GameObject newButton = GameObject.Instantiate (tutorialButton); 

    // Set the parent of the new button (In my case, the parent of tutorialButton) 
    newButton.transform.SetParent (levelButtons.transform); 

    //Set the scale to be the same as the tutorialButton 
    newButton.transform.localScale = tutorialButton.transform.localScale; 

    //Set the position to the right of the tutorialButton 
    Vector3 position = tutorialButton.transform.localPosition; 
    position.x += rect.rect.width*i; 
    newButton.transform.localPosition = position; 
} 

我不完全相信,如果這是正確的做法,因爲它可能會或可能不會給根據不同的屏幕尺寸和畫布意想不到的結果,但希望它給你一個關於動態創建對象的想法。

+0

何處附上此腳本。在畫布或面板? – iappmaker

+0

只要您從inspector中設置tutorialButton和levelButton對象,它實際上並不重要,您附加腳本的位置。它不使用腳本附加的GameObject的任何屬性。 (在我的例子中,我有一個處理所有遊戲邏輯的腳本,它被附加到一個空的GameObject上,並且這段代碼在Start()函數中,所以在每個級別(場景)的加載時它被調用一次創建關卡所需的按鈕)。 – merterpam

1

我不知道這是否有幫助,但如果你在場景中的所有圖像畫布下,這個你只需要拖動該腳本的帆布和使用

//level-1 is to keep the array notation FindObjectOfType<NameOfScript>.ChangeColor(level-1,Color.green);

或者你也可以做

//level-1 is to keep the array notation FindObjectOfType<NameOfScript>.RevertColor(level - 1);

這是腳本:

//Keep it private but you still see it in inspector 
//#Encapsulation :) 
[SerializeField] 
private Canvas _canvas; 

private Image[] _images; 
//keep the original colors in case you want to change back 
private Color[] _origColors; 

void Start() { 
    _images = GetComponentsInChildren<Image>(); 
    _origColors = new Color[_images.Length]; 
    for (int i = 0; i < _images.Length; i++) 
    { 
     _origColors[i] = _images[i].color; 
    } 

} 
//Reverts the color of the image back to the original 
public void RevertToOriginal(int imageIndex) 
{ 
    _images[imageIndex].color = _origColors[imageIndex]; 
} 
//Change to color to the coresponding index, starts from 0 
public void ChangeColor(int imageIndex, Color color) 
{ 
    _images[imageIndex].color = color; 
} 

P.S如果您希望它只在最後可見,您可以創建一個方法,爲畫布啓用=(true或false)。所以你保持它的虛假直到關卡結束,並且當你想要顯示的時候它是真實的,而在每次回答之後你根據結果調用ChangeColor。 爲了更方便您可以使用:

NameOfScript variableName = FindObjectOfType<NameOfScript>(); 

之後,你只需要調用

variableName.ChangeColor(level - 1, Color.green); 

也不要緊,你把劇本。我會在場景中製作某種經理(空GameObject)並將其放在那裏。