- Home /
How do I spawn another object at the position of another?
I am making a horror game that spawns the ghosts behind the player. I have a ghost prefab, and I want it to spawn behind the player when it is called by this script-
var spawn : Transform; //the object that will spawn that causes the scare
var howoften : int = 10; //how often a scare will occur (lower numbers=more freq scares)
private var randomnum = 0; //the random number that is generated
var maxtimewait = 10; //max time between scares
while (true) {
yield WaitForSeconds(Random.Range(maxtimewait, 0));
randomnum = Random.Range(howoften, 0);
if(randomnum < 1) {
audio.Play(); //this is where I would put the spawning function, but I used audio instead to make sure the rest of the script was working
}
}
Can someone help me with a line of script that will spawn the ghost (var spawn) at the location of the spawn cube (have not added that var yet)..
-Thanks
Answer by moghes · Jun 10, 2013 at 10:43 PM
Well if you have this script attached to your player, then it goes like this
var spawn : Transform;
var howoften : int = 10;
private var randomnum = 0;
var maxtimewait = 10;
// newly added variables
var pPos: Vector3; // your player position
var ghostPos : Vector3;
var yourGhost : GameObject;
var distance : float = 1;
while (true) {
yield WaitForSeconds(Random.Range(maxtimewait, 0));
randomnum = Random.Range(howoften, 0);
if(randomnum < 1)
{
pPos= this.transform.position; // get your player position
ghostPos = Vector3(pPos.x , pPos.y , pPos.z - distance);
Instantiate(yourGhost , ghostPos , Quaternion.identity);
}
}
Note that you have to drag you ghost prefab to your yourGhost variable and set a distance value as you wish. I have set a default to be 1 unit.
This script is spawning a ghost at single position...$$anonymous$$y goal is making the ghost spawn at the same coords as another gameobject, no matter if the object moves..thanks for the help though, Its a real start :)
-cheers
Actually, I got it working...thanks again, I will reply to tell you if I had change anything, but I shouldnt (it looks good!)
@sandhillceltic , well if the answer did help you, please just set it as true, by clicking on the tick
Thanks! I upvoted the answer, as it fixed my problem! Totally forgot that!
@sandhillceltic thanks for the upvote, but that does not set the answer as true, any user can see a green icon even before opening the page if the answer is set as true, while he sees a blue icon meaning no correct answer yet.
The icon is locatated below the upvote and downvote icons, its the tick sigh.
Answer by Seizure · Jun 07, 2013 at 08:50 PM
clone = Instantiate (spawn, transform.position, transform.rotation);
Could you please put it in the code, so I can see how I would use it? Thanks