我正在嘗試創建一個程式,該程式將隨機從頂部隨機生成球。問題是它不夠快,但如果我將值更改為 1/2,它會產生 50 超快。
using System.Collections.Generic;
using UnityEngine;
public class SpawnAstroids : MonoBehaviour
{
public GameObject astriod;
public float xBounds, yBounds;
public int playerPoints = 0;
public int enemyPoints = 0;
void Start()
{
StartCoroutine(SpawnRandomGameObject());
}
IEnumerator SpawnRandomGameObject()
{
yield return new WaitForSeconds(Random.Range(1,2)); //Random.Range(1/2, 2)
Instantiate(astriod, new Vector2(Random.Range(-xBounds, xBounds), yBounds), Quaternion.identity);
StartCoroutine(SpawnRandomGameObject());
}
}
uj5u.com熱心網友回復:
Unity C# 要求您指定您的小數具體是浮點數還是雙精度數。添加f到每個十進制數的末尾。例如:Random.Range(0.5f, 2);
(小注Random.Range是包含還是排除取決于您使用整數還是浮點數。)
同樣,當您定義 a 時Vector2 bob = new Vector2(0.5f,0);,f也需要明確表示它是一個浮點數。
uj5u.com熱心網友回復:
Random.Range有兩個多載。
public static float Range(float minInclusive, float maxInclusive);
和
public static int Range(int minInclusive, int maxExclusive);
你傳入
Random.Range(1, 2);
這是兩個int值,因此使用第二個多載,結果將是int介于1和2 - 1...這里沒有很多選項;)
還有你的嘗試
Random.Range(1/2, 2);
又是int價值觀!1/2是一個整數除法,結果為0! 所以這個亂數可以回傳0或1。
您寧愿做的是傳遞float值,例如
Random.Range(1f, 2f);
1這可能導致介于和2或相應地之間的任何浮點值
Random.Range(0.5f, 2);
或回到你的嘗試
Random.Range(1 / 2f, 2);
它現在使用float除法,因此結果自動為 a float,因此將使用第一個多載。
一般來說,不需要遞回地呼叫協程,你可以簡單地回圈永遠并且注意它Start本身可以是一個協程,例如
private IEnumerator Start()
{
while(true)
{
yield return new WaitForSeconds(Random.Range(0.5f, 2f));
Instantiate(astriod, new Vector2(Random.Range(-xBounds, xBounds), yBounds), Quaternion.identity);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/432337.html
上一篇:試圖在碰撞時更改變數
