- Home /
Prefab loses script transform values.
I'm making a platformer and I have objects which when they collide with the player, the player is spawned back at a respawn point. My respawning script on each set of spikes has player and respawn point transform values. However when I make the spikes into a prefab in order to place several of these spikes around the level, the prefab's player and respawn point transform values are lost. Only the originally placed spikes have the values. I know i could just manually add these transforms to each instance of the prefab (each set of spikes in the level) but this would be tedious if I'm going to make many levels.
Sorry for the the noob, this is my first game.
The script for respawn is shown below:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Respawn : MonoBehaviour { [SerializeField] private Transform player; [SerializeField] private Transform respawnPoint;
private void OnTriggerEnter2D(Collider2D other)
{
player.transform.position = respawnPoint.transform.position;
}
}
It's much easier to just give the spikes a tag such as "Spike".
Have an empty gameobject called Respawn point.
Have a script on your player prefab along the lines of:
public void OnCollission(Collider col)
{
if (col.CompareTag("Spike"))
{
transform.position=Respawn.transform.position;
lives-=1;
Instantiate awesome magical particle effect;
}
}
}
Answer by abi-kr01 · Apr 25, 2019 at 11:02 AM
Prefab only have links that are either part of prefab itself or something from project folder like images. When you are generating this prefab in the scene you have to assign the player in
using UnityEngine;
using UnityEngine.UI;
public class Respawn: MonoBehaviour
{
public Transform player;
public Transform respawnPoint;
void Start()
{
player = GameObject.Find("Player");
RespawnPoint=GameObject.Find("RespawnPoint");
}
}
Hope you have only one player and RespawnPoint
I tried all methods suggested to me and this is the only one which worked in my case. Thanks!
Answer by Bunny83 · Apr 25, 2019 at 11:05 AM
Of course. Prefabs are assets. Assets can never reference objects that live in a scene. The objects in a scene are only available when the scene is loaded. If you instantiate the prefab you have to setup any scene object references you need yourself from the instantiating script or let a script on the prefab find the references itself. The first option is the better one. Though common things like respawning shouldn't be handled by individual objects / obstacles. It's common to create some sort of game manager singleton which provides a Respawn method. Any other object can simply call that method on the singleton.
Your answer
![](https://koobas.hobune.stream/wayback/20220612200155im_/https://answers.unity.com/themes/thub/images/avi.jpg)