Unity按下按鈕 產生不重複隨機圖片

views

最近在做個app需要一個按下按鈕後 隨機產生不同圖片 並且不重複的功能

功能需求:

  • 按鈕製作
  • 按下按鈕隨機產生圖片
  • 已出現過的圖片不會再重複出現

JavaScript

#pragma strict

var playBtn: GUIStyle;
var textStyle: GUIStyle;
var poster1: GameObject;
var poster2: GameObject;
var poster3: GameObject;
var poster4: GameObject;
var poster5: GameObject;

private var temp:int=0;
private var counter:int=0;
private var i=0;
private var posterTemp:GameObject;
var posterArray = new Array ();


function Start()
{
  temp=Random.Range(1,6);
}

function OnGUI()
{
  GUI.depth=0;

  //Dispaly play button
  if (GUI.Button (Rect (Screen.width/2-128,Screen.height-64,256,64),"", playBtn)) 
  {
    if (posterTemp) Destroy(posterTemp);
    
    if (posterArray.length>=0 && posterArray.length<=4) //up to 5 postrers
    {      
      //if one of value in array is same as temp value
      //--Keep comapring, untill temp value is not different to any value inside array
      while (temp in posterArray) 
      {
        print("same!");
        print("temp:"+temp+"posterArray:"+posterArray);
        temp=Random.Range(1,6); //pick again
        
      }
      
      //if non of value in array is same as temp value
      if (!(temp in posterArray)) 
      {
        print("different!");
        print("temp:"+temp+"posterArray:"+posterArray);
        RandomPoster();
        posterArray.Add(temp);
      }
    }
    
    if (posterArray.length>4)
    {
      print("Completed!");
    }
  }
  
  GUI.Label (Rect (Screen.width/2-128,Screen.height-64,256,64),String.Format("NEXT"),textStyle);  
}


function RandomPoster()
{
  switch (temp)
   {
      case 1: 
        //show poster
        print("Poster1: "+temp);
        posterTemp=Instantiate (poster1, Vector3(0,0,0), Quaternion.identity);
             break;
      case 2: 
             print("Poster2: "+temp);
             posterTemp=Instantiate (poster2, Vector3(0,0,0), Quaternion.identity);
             break;
         case 3: 
          print("Poster3: "+temp);
          posterTemp=Instantiate (poster3, Vector3(0,0,0), Quaternion.identity);
           break;
       case 4: 
             print("Poster4: "+temp);
             posterTemp=Instantiate (poster4, Vector3(0,0,0), Quaternion.identity);
             break;
        case 5: 
             print("Poster5: "+temp);
             posterTemp=Instantiate (poster5, Vector3(0,0,0), Quaternion.identity);
             break; 
      default:
             Debug.Log ("none of the above");
             break;
   }
}

									

效果示範

Random-non-repeat-image-player

This entry was posted in Unity小技巧, 遊戲開發 and tagged by Mr.M. Bookmark the permalink.


One thought on “Unity按下按鈕 產生不重複隨機圖片

  1. I blog frequently and I truly thank you for your information. The
    article has really peaked my interest. I will take a note of your blog and
    keep checking for new information about once per week.
    I subscribed to your Feed too.

Leave a Reply

Your email address will not be published. Required fields are marked *