在屏幕上随机预制对象

时间:2016-04-18 20:45:55

标签: c# unity3d

这是我第一次来这里;)

我有这个SpawnController:

    using UnityEngine;
    using System.Collections;
    using System.Collections.Generic;
    public class SpawnController : MonoBehaviour {

        public float maxWidth;
        public float minWidth;

        public float rateSpawn;
        private float currentRateSpawn;

        public GameObject tubePrefab;

        public int maxSpawnTubes;

        public List<GameObject> tubes;

        // Use this for initialization
        void Start () {

            for (int i = 0; i < maxSpawnTubes; i++) {
                GameObject tempTube = Instantiate (tubePrefab) as GameObject;
                tubes.Add (tempTube);
                tempTube.SetActive (false);

            }

            currentRateSpawn = rateSpawn;

        }

        // Update is called once per frame
        void Update () {

            currentRateSpawn += Time.deltaTime;
            if (currentRateSpawn > rateSpawn) {
                currentRateSpawn = 0;
                Spawn ();
            }
        }

        private void Spawn() {

            float randWitdh = Random.Range(minWidth, maxWidth);
            GameObject tempTube = null;

            for (int i = 0; i < maxSpawnTubes; i++) {
                if (tubes [i].activeSelf == false) {
                    tempTube = tubes [i];
                    break;
                }
            }

            if (tempTube != null)
                tempTube.transform.position = new Vector3 (transform.position.x, randWitdh, transform.position.z);
            tempTube.SetActive (true);
            }
    }

我想在X AXIS - 9.5上以10.9生成一个预制(随机)管...但是当我玩的时候,预制件在Y轴上产生(ramdomly)在Y轴上-9.5的10.90 ...我的代码出了什么问题?

2 个答案:

答案 0 :(得分:1)

好吧,我真的不明白你的意思,但随机部分确实是在y轴上,而不是x ...

tempTube.transform.position = new Vector3 (transform.position.x, randWitdh, transform.position.z);

所以也许你可以使用randWidth作为第一个参数(x coord)这是你想要的吗?

如果这不是你的意思,它听起来有点琐碎......

答案 1 :(得分:0)

tempTube.transform.position = new Vector3 (transform.position.x, randWitdh, transform.position.z);

我猜你的randWitdh在错误的轴上。

应该是:

tempTube.transform.position = new Vector3 (randWitdh, transform.position.y, transform.position.z);