Problem with Random Spawning
This is my code:
using UnityEngine;
using System.Collections;
public class Spawn : MonoBehaviour {
public GameObject[] walkers;
public int walkeramount;
public GameObject Walker;
public GameObject[] enemies;
public Rigidbody Enemy;
public int enemyamount;
private Vector3 walkerSpawnPoint;
private Vector3 enemySpawnPoint;
// Update is called once per frame
void Update () {
walkers = GameObject.FindGameObjectsWithTag("Walker");
enemies = GameObject.FindGameObjectsWithTag("Enemy");
walkeramount = walkers.Length;
//keeps track of walkers and stores amount.
if(walkeramount != 20)
{
InvokeRepeating("spawnWalker", 5, 10f);
}
if(enemyamount < 30)
{
InvokeRepeating("spawnEnemy", 3, 3f);
}
}
void spawnWalker()
{
walkerSpawnPoint.x = Random.Range(-20, 20);
walkerSpawnPoint.y = 0.5f;
walkerSpawnPoint.z = Random.Range(-20, 20);
Instantiate(Walker, walkerSpawnPoint, Quaternion.identity);
CancelInvoke();
}
void spawnEnemy()
{
enemySpawnPoint.x = Random.Range(-20, 20);
enemySpawnPoint.y = Random.Range(2, 6);
enemySpawnPoint.z = 5;
Instantiate(Enemy, enemySpawnPoint, Quaternion.identity);
CancelInvoke();
}
}
Despite the fact the code runs without error, when the enemies do spawn, the z axis says 5 yet I have another object called player that has a z position of 5 also yet does not sit anywhere near to it. Is there a reason why two objects would not be using the same scale of position? (I have checked and it is definitely the z axis and not another axis).
Answer by Barsonax · Apr 26, 2016 at 07:26 PM
Do the prefabs you are using have the same scale? This might be a cause.
I noticed in your update function you are constantly searching for gameobjects. I think a better system would be to use events to count how many enemies have spawned. I dont think this would matter though performance wise if its a very small game but just so you know. Its pretty bad performance wise to constantly search the scene for gameobjects even if you use tags.
Also unity has some nice build in functions to return random points. Just look in UnityEngine.Random they might suit you more.
Simply go to the folder they are located and select them (inside of unity of course). In the inspector you should be able to see the scale.
Unfortunately it seems i cannot upload a screenshot but it should be easy enough to find. Just look for the transform component in the inspector. It should be in the top right part of your screen.
Your answer
Follow this Question
Related Questions
Spawn system that doesn't instantiated enemies on top of player or each other (C#) 2 Answers
How to rotate an object 2 Answers
Items spawn and will not stop spawning. 2 Answers
How to spawn a prefab when a button with a certain tag is pressed 1 Answer
Make a collision check when spawning with Instantiate 1 Answer