- Home /
Instantiated Object spawning at wrong position
I'm trying to make an object/objects instantiate when OnTriggerEnter is activated.
At first this worked fine, the objects appeared when the trigger was entered just as needed.
Original script-
using UnityEngine;
using System.Collections;
public class HazzardSpawner : MonoBehaviour
{
public GameObject hazzardType;
void OnTriggerEnter()
{
Instantiate (hazzardType, transform.position, transform.rotation);
Destroy(gameObject);
}
}
Now I get a little more technical and want to add a variation along the x axis to where they spawn.
new script- using UnityEngine; using System.Collections;
public class HazzardSpawner : MonoBehaviour
{
public GameObject hazzardType;
public int spawnVariation;
void OnTriggerEnter()
{
Vector3 spawnPosition = new Vector3 (Random.Range (-spawnVariation, spawnVariation), 0, 0);
Instantiate (hazzardType, spawnPosition, transform.rotation);
}
}
It adds the variation along the x axis, but for some reason its also affecting where the objects spawn along the z axis. Every time its spawning the objects about 20 units away from the origin point on the Z axis.
???
This is the trigger(highlighted) and its origin point.
I've added this sphere to show where the objects are now spawning from(y axis)
Im not sure but you always intantiate object on position 0 on Z axis right ?
With the first script yes, right on 0,0,0 every time.
The second script no, the spawnVariation variable allows me to set a $$anonymous$$/max distance along the X axis where the object can spawn randomly.
The random spawning along the x axis works great, but its always spawning about 20 units away from origin on the z axis (and always the exact same distance)
You set your Vector3 spawnposition Z axis to 0, then on instantiate you call spawnposition where is Z 0 so it always spawn your object on position 0, try to use no 0 but tranform.positon.z or something. Im not sure if i understood good your problem.
Answer by Stephanides · Mar 12, 2015 at 11:18 AM
did you try Vector3 spawnPosition = new Vector3(Random.Range(-spawnVariation, spawnVariation),0 , transform.position.z) ?
Answer by Yword · Mar 12, 2015 at 10:12 AM
Maybe you should set the spawnPosition relative to the transform's position.
Vector3 spawnPosition = transform.position + new Vector3 (Random.Range (-spawnVariation, spawnVariation), 0, 0);
didn't work and had the weird side effect of constantly spawning objects (ended up with about 500 clones...lol)
:(
did you try Vector3 spawnPosition = new Vector3(Random.Range(-spawnVariation, spawnVariation),0 , transform.position.z) ?
Oops.. must have skipped over your comment, never noticed it.
Yes that fixed it. Want to edit your reply and put it as an answer, I'd be happy to up-vote it for you.
Thanks
:)
Answer by Prosun · Jun 26, 2016 at 09:29 AM
i have the same type of issue :(
this is the link of the video which i'm facing right now...