- Home /
(solved)Instantiate prefab "on top" of previous one
Hey everyone! As a coding beginner, I'm stuck with this problem, and I bet you guys can help me out easily.
I have several Prefabs containing a plane with an animated textures on it. When I press the corresponding keyboard button, a clone gets instantiated ( f.ex. I press the spacebar -> prefab_1 gets instantiated). If I press another keyboard key, the newer instantiated prefab should be placed "on top" ( +1 on the z-axis) of the previous instantiated prefab and so on...
I do have managed to get the instantiation of the prefabs, but I'm stuck with the +1 on the z-axis / "on top" part. right now, they have a fixed "spawn" position.
Here's my code:
using UnityEngine;
using System.Collections;
public class Ccontroller : MonoBehaviour {
public Rigidbody ani01;
public Rigidbody ani02;
void Update() {
if (Input.GetButtonDown("Fire1")) {
Rigidbody clone;
clone = Instantiate(ani01, new Vector3(0, 0, 3),Quaternion.identity) as Rigidbody;
}
if (Input.GetButtonDown("Fire2")) {
Rigidbody clone;
clone = Instantiate(ani02, new Vector3(0, 0, 3),Quaternion.identity) as Rigidbody;
}
}
}
additional info: It's an orthographic camera in the scene and all the prefabs have a script attached, which give them a tag and destroys older clones of the same prefab in the scene when the same button is pressed twice. so there is always just 1 clone of the same prefab in the scene.
If you guys could help me out, that would be super awesome!
Answer by Cherno · May 19, 2015 at 03:47 PM
Decalre an int variable in the main body, and increase it by one every time a prefab gets instantiated. Make the Instantiate function's position parameter use the int value as the Vector3's y value.
using UnityEngine;
using System.Collections;
public class Ccontroller : MonoBehaviour {
public Rigidbody ani01;
public Rigidbody ani02;
public int currentHeight = 0;
void Update() {
if (Input.GetButtonDown("Fire1")) {
Rigidbody clone;
clone = Instantiate(ani01, new Vector3(0, currentHeight, 3),Quaternion.identity) as Rigidbody;
currentHeight ++;
}
if (Input.GetButtonDown("Fire2")) {
Rigidbody clone;
clone = Instantiate(ani02, new Vector3(0, currentHeight, 3),Quaternion.identity) as Rigidbody;
currentHeight ++;
}
}
}
Hey Cherno! thanks for posting this! It's working prefectly! I just had to use another axis but all cool! Thanks man, made my day!!
Your answer
Follow this Question
Related Questions
Instantiate Reference Problem 1 Answer
Cloning Objects with Instantiate() - variables/references for added Components not stored? 3 Answers
Following Object can't find newly Instantiated Object (Solved) 1 Answer
Destroy a specific instantiated clone? 2 Answers
When cloning, how do you make your clones keep the original properties? 2 Answers