Respawn not working past 2nd respawn
Hey all,
I'm attempting to respawn an object in it's original spot once it's destroyed. It seems to work the first time but it's not working past that. I see what's going on, for some reason the clone does not have the objects I've attached to the original objects script.
For a little context, I'm dragging this object onto a character. Once it hits him I want the object to be destroyed and a replacement to respawn in the objects original place.
Is there something I need to do to ensure the clones call these objects? I've attached my code below.
public GameObject fishFood; //= GameObject.Find ("Food");
public Transform fishFoodSpawn;
public Vector2 spawnLocation = new Vector3 (-3.88f, 2.44f, 0f);
private bool dragging = false;
private float distance;
void OnMouseDown()
{
distance = Vector2.Distance(transform.position, Camera.main.transform.position);
dragging = true;
}
void OnMouseUp()
{
dragging = false;
}
void Update()
{
if (dragging)
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Vector2 rayPoint = ray.GetPoint(distance);
transform.position = rayPoint;
}
}
// Destroy the food once it enters the bears mouth area
void OnTriggerEnter2D (Collider2D other)
{
if (other.tag == "Bear")
Destroy (gameObject);
}
void OnDestroy() {
Instantiate (fishFood, spawnLocation, Quaternion.identity);
}
}
Thanks in advance!
I've found a solution. Though it seems like a bit of a hack and I'm sure there's a cleaner way to handle this it works.
So I've created a duplicate of the object that needs respawning. Attached the duplicate to the script as the object to respawn and attached the original object to that corresponding slot on the duplicate object. That way the object is not respawning itself, I believe that was the core of my issue.
I may run into problems later with this hack but nothing I can foresee being that I'm so new to C#
If anyone knows of a more proper way to handle this please let me know!
Answer by Python_Regex1023 · Jun 11, 2016 at 02:18 PM
@maydaywray , Actually, since you don't have a set wait time between each respawn, a cleaner way would be to simply to move the transform of the your GameObject back to the spawn transform, like so
using UnityEngine;
using System.Collections;
public class Example : MonoBehaviour {
public Transform fishFoodSpawn;
//Declare other variables
//Put other functions here
void OnTriggerEnter2D (Collider2D other) {
if(other.tag == "Bear")
Respawn();
}
void Respawn () {
gameObject.transform.position = fishFoodSpawn.position;
Debug.Log("You Died");
}
}
I tested this and it seems to work for me, but in case you have a Rigidbody attached to this GameObject you may want to store a reference to said Rigidbody and then set velocity to 0. I hope this helps!