Random generation

I want to create a tube spawning mechanic.
I had something done, but for some reason it does not want to go in the direction I want it to go.
It also does not go further then one object, it just spawns in one another.

Code:
using UnityEngine;
using System.Collections;

public class TubeCreation : MonoBehaviour {
	public GameObject tubeObject = null;
	public float add = 100000f;

	void Update () {
		Debug.Log("<color=blue>Info:</color> Object Created");
		tubeObject = Instantiate (Resources.Load ("Prefabs/prefab_tube"), new Vector3(0,0,287),Quaternion.Euler(0,90,270)) as GameObject;
		tubeObject.transform.Translate(Vector3.right * add * Time.deltaTime);
	}
}

My ships model is backwards. So I use back to go forward, please keep that in mind.

Quite a few things to note:

  • Instantiation on each frame is quite expensive, performance-wise.
  • Instantiation with Resource.Load frequently is even worse.

Solution:
You should be using the public GameObject variable in order to assign your prefab from the project folder. Also, you shouldn’t instantiate per frame, in this case, this doesn’t seem to make sense anyway, unless you need ~ 50-60 tubes to be spawned per second, which i doubt.

  • You’ve got a fixed value for the vector’s z-value.
  • When you feel like multiplying Time.deltaTime with such a huge number, there’s often something wrong (not always).

In order to simplify all that, use an integer or float variable which starts with the first z-value, or use a Vector3 in order to store x,y,z at once.
Take another variable that defines your offset for each instantiation (float, int or Vector3, just as you like).

I fixed a few things and added a key input for the spawn control, play around with it and you’ll get the idea. The current offset is 1 unit in x-direction for testing purposes with Unity’s built-in cube.

Here’s the code:

using UnityEngine;

public class NewBehaviourScript : MonoBehaviour
{
    // drag the prefab from the project folder in the inspector slot
    public GameObject tubeObject;
    // current startPosition (I've chosen 0,0,0 here)
    public Vector3 nextSpawnPosition = Vector3.zero;
    // the offset 1,0,0 
    public Vector3 offset = Vector3.right;

    void Update()
    {
        // only instantiate when space bar is pressed
        if(Input.GetKeyDown(KeyCode.Space) && tubeObject != null)
        {
            Instantiate(tubeObject, nextSpawnPosition, Quaternion.Euler(0, 90, 270));
            // add the value to the spawnPosition
            nextSpawnPosition += offset;
        }
    }
}