2016-06-27 85 views
1

我試圖創建一個腳本,我可以生成不同類型的對象菌種不同類型的對象

+1

是否要保證10個對象中的2個是一種類型還是您正在尋找純粹的機會?我可能會實現這個作爲枚舉數返回對象類型/實例化對象 – Charleh

+0

我想保證即使只有一個它會產生對象2號。我只需要被產生。因爲它有一種特殊的能力,對象1號正常。 – John

+0

你可能想按照你需要的比例將對象添加到列表中,我會選擇一個比例,比如說2:8,然後是一個數字,比如10,20等,將項目的數量添加到按指定的比例列表,然後從列表中隨機選取項目,在挑選項目時將其刪除 – Charleh

回答

1

從您的描述和評論聽起來是什麼,你要保證speiclaCratePercentageMinspeiclaCratePercentageMax之間的百分比是特殊的創造,但其餘可以只是一個正常的創建。如果這是你所需要做的就是弄清楚這個百分比將會佔總數的多少,首先產生許多箱子,然後用普通箱子填充剩下的箱子。

using UnityEngine; 
using System.Collections.Generic; 
using UnityEngine.UI; 

public class spawnmanager : MonoBehaviour { 

public int noOfobjects = 6; 

public Transform[] spawnPoints; 

public GameObject normalCrate; 
public GameObject specialCrate; 

public float speiclaCratePercentageMin; 
public float speiclaCratePercentageMax; 

void Awake() 
{ 
} 

// Use this for initialization 
void Start() 
{ 
    spawner(); 
} 

void spawner() 
{ 
    List<Transform> availablePoints = new List<Transform>(spawnPoints); 

    //Figures out how many special creates we need. 
    int numberOfSpecialCrates = noOfobjects * Random.Range(this.speiclaCratePercentageMin, this.speiclaCratePercentageMax); 

    //Added i<spawnPoints.Length check to prevent errors when noOfobjects is bigger than the number of available spawn points. 
    for (int i = 0; i<noOfobjects && i<spawnPoints.Length;i++) 
    {  
     int spawnPointIndex = Random.Range (0, availablePoints.Count); 

     //As long as i is lower than numberOfSpecialCrates we spawn a special crate. 
     if(i < numberOfSpecialCrates) 
     { 
      Debug.Log("dd"); 
      Instantiate(specialCrate, availablePoints[spawnPointIndex].position, Quaternion.identity); 
     } 
     else 
     { 
      Instantiate(normalCrate, availablePoints[spawnPointIndex].position, Quaternion.identity) ; 
     }  

     availablePoints.RemoveAt(spawnPointIndex); 
    } 
} 
} 
+0

太棒了!它解決了這個問題:)現在,如果他們被摧毀,我該如何跟蹤障礙物?例如,如果場景中只有2個障礙物,我想更多地產生,如果你知道的話,請與我分享你的信息,如果不是的話,非常感謝:) – John

+0

@Groude標記所有具有相同標記的物體,然後使用函數[搜索標籤中的對象](https://docs.unity3d.com/ScriptReference/GameObject.FindGameObjectsWithTag.html),當你有更少的產卵。 –

+0

您也可以使用存儲對象所有實例的列表。 (或者兩個,如果這樣可以更容易地檢查當前存在多少個罕見的問題) –

0

我認爲這個問題是在這裏 如果(randomFloat> = 1 || randomFloat < = 0.9f & &的randomFloat> = 0.7F)

更好地使用多個托架

如果(randomFloat> = 1 ||(randomFloat < = 0.9f & & randomFloat> = 0.7F))

+0

它使它更好,但不知何故,它有時會產生4或5個障礙而不是產卵6 – John

+0

你的代碼是基於隨機的,偶然你可能會得到600左右的1000但不是6的十個 – amin

+0

隨機的職位,但類型即時試圖做的百分比 – John

0

退房this SO想法的問題。這似乎是你在找什麼。

+0

鏈接只有答案是不鼓勵,即使其他SO問題。要麼這個問題是不同的,這個問題應該是它自己的答案的完整版本,否則他們是相似的,你應該投票將它作爲一個副本關閉。 –