- Home /
Respawn question
I am trying to make a game, where if you walk into a certain point (pre-defined with a trigger collider) and it will set that location as your next spawn point if you were to die.
My idea for this to work was to have have a collider with Is Trigger selected, place it around the area i want, then tag it as Marker1 (as i am just testing this to get it to work) and have it so if it is Marker1 it will overwrite the default spawn point with that one. I got all that to work, but i do not know the correct syntax of the code i am trying to write.
I am trying to write:
transform.position = GameObject.Find(spawnpoint).transform.position;
Though this is the wrong syntax. Also 'spawnpoint' would be a string. I would attach this to the player, so it would set the players position the the position of whatever spawnpoint is. So please help me out...
Answer by Murcho · Feb 27, 2010 at 11:10 PM
You would probably be best off having a script that tracks where the player should respawn. It should hold a reference to the current respawn transform, and that reference should be updated as the player walks into each respawn trigger.
eg. RespawnTracker.cs
Transform currentRespawnPos;
public void SetNewRespawn(Transform newRespawn) { currentRespawnPos = newRespawn; }
public Transform GetRespawnPosition() { return currentRespawnPos; }
Then have this script on each of the respawn triggers
RespawnTrigger.cs
// Hold reference to the RespawnTracker // Either drag and drop the reference in editor or write some code to set it RespawnTracker respawnTracker;
void OnTriggerEnter(Collider other) { // You will need to fill this out with a proper test suitable to your project // Read as psuedo code if(other == player) { respawnTracker.SetNewRespawn(transform); } }
From there, the player just needs to call the respawn tracker to get the position of the last checkpoint.
Just as a quick note, using GameObject.Find() during the game's runtime can be very slow, especially as you get more and more objects in your scene. It is better to find anything you can at the start of loading a level, or store references by dragging them onto scripts during editing where possible.
Yeah...this really doesn't help me as i do not understand C#. Thanks for the effort though.
Answer by Ashkan_gc · Feb 28, 2010 at 03:07 PM
create a script for your player and write a code like this
function OnTriggerEnter (other : Collider)
{
if (other.name == "spawnpoint")
{
this.spawnPosition = other.transform.position;
}
}
just set the name of all spawn point gameObjects to "spawnpoint" also in the script that you create declare a variable as spawnPosition. when you die just set
transform.position = spawnPosition;