- Home /
Finding object via script
In one of my scripts, I am trying to get an object to respawn when it collides with my death boundary. The collision works, and the character loves a life, but it won't move to it's spawnpoint. I should probably show snippets of my code so you guys can understand better:
var spawnpointobject:GameObject;
var spawnpoint:Transform;
function Start() {
gameObject.tag = "Player";
transform.position=spawnpoint.transform.position;
spawnpointobject = gameObject.Find("P1Spawn");
spawnpoint = spawnpointobject.transform;
}
function OnDeath () {
stock--;
transform.position = spawnpoint.position;
}
When my character collides with my death boundary, a stock is removed, So I know that it's being called. But it keeps falling. I put in a Debug.Log(spawnpointobject) in the Update function, and it always returns null. I realise, I'm probably over complicating things, but I'm just trying to get it to work. Oh, and my spawn object is called P1Spawn, and it's at the regular level in the Hierarchy along with the character, when it's created.
"And the character loves a life" - That has to be the most uplifting thing I read today :) I love life too!
Answer by Statement · Mar 28, 2011 at 09:51 PM
This line of code...
transform.position = spawnpoint.transform.position;
... might throw an exception (if spawnpoint is null to start with). That means that any following code in that method will not be run, so it will never even call Find. Also...
spawnpointobject = gameObject.Find("P1Spawn");
... should be:
spawnpointobject = GameObject.Find("P1Spawn");
Also make sure you ain't creating P1Spawn in any other Start method because otherwise it might be created after you try to find it. However you could probably make things much much simpler like this:
function OnDeath () {
stock--;
transform.position = GameObject.Find("P1Spawn").transform.position;
}
It's not likely death happens every frame so it's ok to look for the spawn once it is called.
If it still doesn't work, make sure your objects name really is P1Spawn and that it is active. Otherwise it won't be found.
Imo, your script could be rewritten as:
gameObject.tag = "Player"; Respawn();
function OnDeath () { stock--; Respawn(); }
function Respawn() { transform.position = GameObject.Find("P1Spawn").transform.position; }
Your answer
Follow this Question
Related Questions
Make Deaths end game 1 Answer
Whats Wrong with my code? 1 Answer
How to make an enemy respawn? 0 Answers
Respawning script question. 1 Answer
How do I make a respawn system? 1 Answer