I want the FPS mini game i’m making on Unity replayable, is there any way I can make my target prefabs spawn into random areas of the game?
GameObject obj = (GameObject)Instantiate(prefab,new Vector3(Random.Range(a,b),Random.Range(a,b),Random.Range(a,b)),Quaternion.identity);
Now you need to give values to a’s and b’s so that object does not get instantiated outside the boundaries of your game.
Edit: Instead of totally random, you could have an array of position that you randomly choose from. For instance, add an empty object to your scene, tag it as SpawnPoint. Create a prefab and drag and drop the empty object into it.
Remove the original one from the scene.
Now from your new prefab start placing them in the scene where you would like your objects to be created. Place them high enough so that your newly instantiated object is not halfway through which would make it fall down below the terrain. You could also place them behind a wall or any environment thing that would hide the instantiation.
Now, in your object to be created add a script like this:
Vector3[] = vecArray;
int top;
void Start(){
GameObject objs = GameObject.FindGameObjectsWithTag("SpawnPoint");
foreach(GameObject obj in bjs){
vecArray = objs.GetComponent<Transform>().position;
}
top = vecArray.Length;
InvokeRepeating("CreateObject",0.01f,10.0f);
}
void CreateObject(){
Instantiate(prefab,vecArray[Random.Range(0,top)],Quaternion.identity);
}
Now I see coming the “I don’t use C#” So same is:
var vecArray:Vector3[];
var top:int;
function Start(){
var objs = GameObject.FindGameObjectsWithTag("SpawnPoint");
for (var obj in objs){
vecArray = obj.GetComponent(Transform).position;
}
top = vecArray.Length;
InvokerRepeating("CreateObject",0,01f,10.0f)
}
function CreateObject(){
Instantiate(prefab,vecArray[Random.Range(0,top)],Quaternion.identity);
}
It will take generate a random value for the index of the array and will get the Vector3 stored there. InvokeRepeating will call the CreateObject function from the start of the scene and every 10s will spawn a new object.
Will I also need to put a y value as I don’t want the target to go to high so the player can’t hit it. Also is that Javascript?