这是一些实例化两种不同类型的预制件并将它们放在随机位置的代码。预制件实例化,但不要随机实例化。我怎样才能解决这个问题???
using UnityEngine;
using System.Collections;
public class Spawner : MonoBehaviour {
// Use this for initialization
void Start () {
InvokeRepeating ("SpawnAThing", 3.0f, 3.0f);
}
// Update is called once per frame
void Update () {
}
void SpawnAThing(){
GameObject x=null;
int z = Random.Range (0, 2);
switch (z) {
case 0:
x = (GameObject)Instantiate(Resources.Load("BadCircle"));;
break;
case 1:
x = (GameObject)Instantiate(Resources.Load("GoodCircle"));
break;
}
x.transform.position.Set (Random.Range (-Screen.width, Screen.width), Random.Range (-Screen.height, Screen.height), 0.0f);
}
}
答案 0 :(得分:4)
由于使用了transform.position.Set()
position.Set()
无法修改位置,因为它不会返回该位置的引用。它返回一个副本。
使用x.transform.position = new Vector3(x,y,z);
所以你要做的就是替换
x.transform.position.Set (Random.Range (-Screen.width, Screen.width), Random.Range (-Screen.height, Screen.height), 0.0f);
与
x.transform.position = new Vector3(Random.Range(-Screen.width, Screen.width), Random.Range(-Screen.height, Screen.height), 0.0f);
编辑:
您现在无法看到它,因为Screen.width
和Screen.height
对于屏幕太过分了。您必须使用Camera.main.ViewportToWorldPoint
将查看转换为世界点,然后您可以使用 0 到 1 表示以 .5 为中间点的屏幕。
如果没有看到,请减少传递到Z轴的15。
x.transform.position = Camera.main.ViewportToWorldPoint(new Vector3(Random.Range(0f, 1f), Random.Range(0f, 1f), Camera.main.nearClipPlane + 15f));
答案 1 :(得分:0)
创建一个GameObject并将其重命名为“SpawnController”并附加此脚本:
using UnityEngine;
public class SpawnController : MonoBehaviour {
//Set at inspector new Min and Max X axis Range.
public float maxWidth;
public float minWidth;
//Set at inspector new Min and Max Y axis Range
public float maxHeight;
public float minHeight;
//Set at inspector new Min and Max Z axis Range (3D game)
public float maxDepth;
public float minDepth;
//Set the time at inspector you want the object to be created eg: every 10 seconds
public float rateSpawn;
private float currentRateSpawn;
// Drag to inspector your gameObject what you want instatiate
public GameObject gameObject;
void Update () {
currentRateSpawn += Time.deltaTime;
if (currentRateSpawn > rateSpawn) {
currentRateSpawn = 0;
Spawn ();
}
}
private void Spawn() {
//Define new (Min and Max) range values for the Vector3 AXIS
float randWitdh = Random.Range(minWidth, maxWidth);
float randHeight = Random.Range(minHeight, maxHeight);
float randDepth = Random.Range(minDepth, maxDepth);
//Vector3 now has a new random range value
Vector3 random = new Vector3(randWitdh, randHeight, randDepth );
//Object will dynamically instantiate according to the values established in the inspector
Instantiate (gameObject, random, Quaternion.identity);
}
}