2017-03-09 69 views
0

我試圖做一個皮納塔遊戲對象,當點擊突發並給出可變數量的禮物GameObjects與各種圖像和行爲在他們。行動中產卵精靈

我也不確定這是什麼統一詞彙,以便在統一文檔中查看這個。

任何人都可以請借我一隻手在這裏?謝謝!

回答

1

有幾種方法可以解決這個問題。 簡單的方法是使用Object.Instantiate,Object Instantiation是你所追求的詞彙。 這將創建一個預定義Unity對象的副本,這可以是一個gameobject或從UnityEngine.Object派生的任何其他對象,請參閱文檔以獲取更多信息https://docs.unity3d.com/ScriptReference/Object.Instantiate.html

在你的情況下,你的皮納塔將有一個預製數組或列表。這些預製是由你爲每一個行爲和精靈創建的。當皮納塔爆發時,你可以在皮納塔周圍的隨機位置實例化隨機預製件,直到你如何定位這些物件。

東西沿着這些線路應該做的伎倆:

class Pinata : Monobehaviour 
{ 
    public GameObject[] pickupPrefabs;   

    public int numberOfItemsToSpawn;  //This can be random  

    //any other variables that influence spawning 

    //Other methods 

    public void Burst() 
    { 
     for(int i = 0; i < numberOfItemsToSpawn; i++) 
     { 
      //Length - 1 because the range is inclusive, may return 
      //the length of the array otherwise, and throw exceptions 

      int randomItem = Random.Range(0, pickupPrefabs.Length - 1); 

      GameObject pickup = (GameObject)Instantiate(pickupPrefabs[randomItem]); 

      pickup.transform.position = transform.position; 

      //the position can be randomised, you can also do other cool effects like apply an explosive force or something 


     } 
    } 
} 

裸記住,如果你想在遊戲中是一致的,那麼每個行爲預製必須有自己的預定義的精靈,這將不會是隨機的。隨機產生的唯一東西就是產卵和定位。

如果你確實想爲隨機化行爲的精靈,那麼你就必須把它添加到皮納塔類:

 public class Pinata : Monobehaviour 
     { 
      //An array of all possible sprites 
      public Sprite[] objectSprites; 

      public void Burst() 
      { 
       //the stuff I mentioned earlier 

      int randomSprite = Random.Range(0, objectSprites.Length - 1); 

      SpriteRenderer renderer = pickup.GetComponent<SpriteRenderer>(); 
      //Set the sprite of the renderer to a random one 
      renderer.sprite = objectSprites[randomSprite]; 

      float flip = Random.value; 

      //not essential, but can make it more random 
      if(flip > 0.5) 
      { 
        renderer.flipX = true; 
      } 
      } 
     } 

可以使用統一隨機爲您的所有需求隨意,https://docs.unity3d.com/ScriptReference/Random.html

希望這會讓你朝着正確的方向前進。

+0

超酷。謝謝! –