2017-05-09 331 views
1

我在每隔1秒間隔後實例化一個特定的預製。this.transform.position + new Vector3(0,y,0)更改遊戲對象的z軸

float y = Random.Range(-0.5f, 1f); 
GameObject newObject = Instantiate (this.prefabToSpawn, this.transform.position + new Vector3(0,y,0),Quaternion.identity); 

每次我實例,我只是想改變沿y遊戲對象的位置 - 軸,但是如果我添加上面的代碼中,新的遊戲目標更進了後面沿z - 軸(甚至在y軸上也有一個隨機變化,雖然它似乎工作正常,但它只需要保留它的z位置),因此不會再出現在場景中。我哪裏錯了?

回答

1

您正在將新的Vector3添加到this.transform.position。問題是this.transform.position會改變你的x,y和z軸。如果您不希望發生這種情況,則必須創建一個臨時Vector3變量,您將存儲transform.position + new Vector3(0, y, 0);的結果,然後您只需修改Z軸並將其設置爲0或您希望它保留的值。

float YOUR_DEFAULT_Z = 0f; 
float y = UnityEngine.Random.Range(-0.5f, 1f); 
Vector3 tempPos = transform.position + new Vector3(0, y, 0); 
//Overide the Z axis 
tempPos.z = YOUR_DEFAULT_Z; 

GameObject newObject = Instantiate(prefabToSpawn, tempPos, Quaternion.identity);