- Home /
trying to instantiate object
im trying to make a flappy bird type game and i used this script in order to instantiate the pipes infinitely : using System.Collections; using System.Collections.Generic; using UnityEngine;
public class pipespawner : MonoBehaviour { public float maxtime = 1; private float timer = 0; public GameObject pipe; public float height; // Start is called before the first frame update void Start() {
}
// Update is called once per frame
void Update()
{
if (timer > maxtime)
{
GameObject newpipe = Instantiate(pipe);
//newpipe.transform.position = transform.position + new Vector3(0, Random.Range(-height, height), 0);
Destroy(newpipe, 15);
}
timer += Time.deltaTime;
}
}
the pipes kinda stack on top of each other and look like this:
need help trying to understand this whole instantiate thing
Answer by metalted · Dec 09, 2021 at 09:38 PM
Check the page for instantiation: https://docs.unity3d.com/ScriptReference/Object.Instantiate.html
A simple example for instantiation would be as follows:
GameObject someObject;
public void Start(){
for(int i = 0; i < 10; i++)
{
GameObject.Instantiate(someObject, new Vector3(i, 0, 0), Quaternion.identity);
}
}
The first parameter is the object you want to instantiate. The second parameter is the position of the object, and the third is the rotation. Quaternion.identity is basically the same as Vector3.zero for rotations. It will just align to the world grid. There are many forms of the Instantiate function so you should read the page to see what fits you best. The above piece of code will just spawn the object 10 times, each shifted 1 unit on the x-axis. Also, dont forget to reset your timer once you spawn something in. Otherwise when the timer is above the max, it will spawn something every frame.
Your answer
Follow this Question
Related Questions
is unity save some cache for game performance ? 1 Answer
Can only move forward or back, no left or right. 1 Answer
How to make projectiles shoot diagonally? 1 Answer
Optimizing a massive array of GameObjects pls help 1 Answer
How to handle Instantiation and Destroying on an infinite runner? 1 Answer