Duplicate an object if is at a position
I have to duplicate an 2D Rigidbody if it's at a specific position. How can i do it? I must use 2D Vector or 3D?
Thank to all in advance.
Answer by Highwalker · Apr 13, 2016 at 07:43 PM
if (transform.position == targetPosition) {
GameObject newObj = new this.gameObject;
Instantiate (newObj, transform.position, Quaternion.identity);
}
Alternatively, you can set it inside a trigger placed wherever your target position is.
Answer by Ciceri · Apr 15, 2016 at 06:04 PM
I use this code, but it doesn't work:
using UnityEngine;
using System.Collections;
public class Duplicate : MonoBehaviour {
public Rigidbody2D ballrigid;
public GameObject ball;
public Vector3 target;
public Vector3 start;
private Vector3 position;
public Quaternion rotation;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
position = new Vector3 (0, transform.position.y, transform.position.z);
if (Input.GetKeyDown(KeyCode.A)){
Instantiate (ball, start, rotation);
}
}
}
Try storing a new ball in a temp variable
GameObject newObj = new ball;
Instantiate (newObj, transform.position, Quaternion.identity);
sorry the right code is : using UnityEngine; using System.Collections;
public class Duplicate : $$anonymous$$onoBehaviour {
public Rigidbody2D ballrigid;
public GameObject ball;
public Vector3 target;
public Vector3 start;
public Vector3 position;
public Quaternion rotation;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
position = new Vector3 (0, 0, 0);
if (ballrigid.transform.position.x == position.x){
Instantiate (ball, start, rotation);
}
}
}
I'm sure that the problem isn't about the instantiate function, because if i try to put in the if statement (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.A)) when i press "A" the object is duplicated in the correct position.
Well the get$$anonymous$$eyDown method simply returns true or false. So anything that'll return true will trigger it the same. I'm guessing the problem is that you check if the balls x position is equal to zero. So if it's 0.001, it will still return false. You could check for a range, so something like
if (transform.position.x > 0 - range && transform.position.x < 0 + range) {
//Instantiate
}
Or you could simply use a trigger. So create an empty object, and add a collider to it. Check isTrigger. And create a script for that object (the object with the trigger) with
void OnTriggerEnter (Collider col) {
//Instantiate
}