Reputation: 11
I am destroying two objects and when they are destroyed I want to instantiate an object at the same location.
public class GameManager : MonoBehaviour
{
public static GameManager instance;
public GameObject prefab;
public void Awake()
{
instance = this;
}
public void Update()
{
Check();
}
public void Check()
{
if (MagnetBehaviour.instance.isConnected == true)
{
Debug.Log("Check");
MagnetBehaviour.instance.isConnected = false;
Instantiate(prefab);
Debug.Log(MagnetBehaviour.instance.isConnected);
}
}
}
Upvotes: 0
Views: 146
Reputation: 31
You should clarify in your question that you are using Unity3D and that the objects you are referring to are Gameobjects in Unity3D.
In your code where you call the Destroy(myGameobject) you can also instantiate the new gameobject you want.
Something like this.
public Gameobject myNewGameObjectPrefab; //drag your prefab here in the inspector
void DestroyAndCreate(Gameobject myGameObject)
{
GameObject newObj = Instantiate(myNewGameObjectPrefab, myGameobject.transform.position);
Destroy(myGameobject);
}
Upvotes: 3
Reputation: 3576
You could attach a script like this to the object you intend to destroy
using UnityEngine;
public class DestroyableObject : MonoBehaviour
{
public bool Destroyed { get; set; }
public Vector3 Position { get; set; }
private void OnDestroy()
{
Position = transform.position;
Destroyed = true;
}
}
Then in your code
public DestroyableObject obj1;
public DestroyableObject obj2;
public void Check()
{
if (obj1.Destroyed && obj2.Destroyed)
{
Instantiate(prefab, obj1.Position, Quaternion.identity);
}
}
Upvotes: 0
Reputation: 73
You are going to have to cache the position of the object before it gets destroyed and instantiate the object that you want to spawn with the cached position. This following script would work for position only. (Untested)
public class GameManager : MonoBehaviour
{
public static GameManager instance;
public GameObject prefabToDestroy;
public GameObject prefabToSpawn;
public void Start()
{
DestroyAndSpawn(prefabToDestroy, prefabToSpawn);
}
public void DestroyAndSpawn(GameObject prefabToDestroy, GameObject prefabToSpawn)
{
Vector3 position = prefabToDestroy.transform.position;
Destroy(prefabToDestroy);
Instantiate<GameObject>(prefabToSpawn, position, Quaternion.Identity);
}
}
If you want the spawned object to have the same rotation as the destroyed one, you can also cache the rotation and replace the Quaternion.Identity with this rotation.
Upvotes: 1