- Home /
How to instantiate a sprite after it has been destroyed?
I am making a pacman clone and i was wondering how i would. respawn pacman to the centre of the maze (14,15) after he has been killed by a ghost.` public Transform[] waypoints; // make an array of preset waypoints for the ghost to follow int cur = 0; // a counter to move through each of the waypoints
public float speed = 0.3f;
// Update is called once per frame
void OnTriggerEnter2D(Collider2D co)
{
if (co.name == "Pacman")// if the ghost collides with pacman
{
if (Health.health > 0)// and the number of lives that pacman has is bigger than 0
{
Destroy(co.gameObject);//destroy the pacman sprite
Health.health -= 1;//remove one from the number of hearts pacman has
Debug.Log("blinky hit pacman");
}
}
}
void FixedUpdate()
{
// Waypoint not reached yet? then move closer
if (transform.position != waypoints[cur].position)
{
Vector2 p = Vector2.MoveTowards(transform.position,waypoints[cur].position,speed);//move towards the next waypoint
GetComponent<Rigidbody2D>().MovePosition(p);
}
// Waypoint reached, select next one
else cur = (cur + 1) % waypoints.Length;
// Animation
Vector2 dir = waypoints[cur].position - transform.position;
GetComponent<Animator>().SetFloat("DirX", dir.x);// change the animation parameters to allow the correct
//animations to play
GetComponent<Animator>().SetFloat("DirY", dir.y);
}`
This is the code i a using to make the Ghosts move around and i would like to re-instantiate pacman inside the OnTriggerEnter2D function
Answer by The_Three_Vs · Apr 01, 2020 at 08:36 PM
Save pac-man to a variable with GameObject pm = co.gameObject;
. Then, after destroying him, call Instantiate(pm, new Vector2(14f, 15f), Quaternion.identity);
This will create another pac-man at the center of the maze with zero rotation.
Hope this helps!
Answer by GrayLightGames · Apr 01, 2020 at 10:47 PM
One option would be, don't destroy pac-man... you could have a dead sprite that you switch to, or call gameObject.SetActive(false). When you're ready to respawn, you just set the position of the object to the correct position and SetActive(true). This is a little safer(and easier) because if you re-instantiate, you'll need to relink pac-man to whatever objects reference him. If you really need to re-instantiate, I would recommend using a Prefab and then instantiating off of that. Good luck!
Your answer
Follow this Question
Related Questions
How to make objects spawn at the same time without colliding ? 1 Answer
[SOLVED]: Bullets passing through platforms - Brackeys Tutorial 1 Answer
how to prevent an gameobject of instantiating if theres an collider where it is supposed to collide 1 Answer
Distribute terrain in zones 3 Answers
How Can I Make My Fire Effect Disappear After I Shoot Object? 1 Answer