Hi guys I am trying to get my enemy to spawn in different locations in my scene and I found a script on Unity3dstudent done by Will Goldstone and it was written in JavaScript. However I have now converted it to C# and got rid of all the errors. I have created 3 empty game objects in my scene in different locations, my script is not attached to anything however on the script it now has three empty transforms like spawn1, spawn2, spawn3 and have dragged my enemy prefab on all slots but when I play the game no enemies are spawning. Can anyone help to see where I am going wrong as I am not sure and gone over the code or does this script need to be attached to some other object to work ![]()
using UnityEngine;
using System.Collections;
public class Spawning : MonoBehaviour
{
float timer = 0.0f;
bool spawnEnem = false;
Rigidbody prefab;
public Transform spawn1;
public Transform spawn2;
public Transform spawn3;
//Transform location;
// Update is called once per frame
void Update ()
{
//check if spawning at the moment, if not add to timer
if(!spawnEnem)
{
timer += Time.deltaTime;
}
//when timer reaches 2 seconds, call Spawn function
if(timer >= 2)
{
StartCoroutine (Spawn());
}
}
IEnumerator Spawn ()
{
//set spawning to true, to stop timer counting in the Update function
spawnEnem = true;
//reset the timer to 0 so process can start over
timer = 0;
//select a random number, inside a maths function absolute command to ensure it is a whole number
int randomPick = Mathf.Abs(Random.Range(1,4));
//create a location 'Transform' type variable to store one of 3 possible locations declared at top of script
Transform location = null;
//check what randomPick is, and select one of the 3 locations, based on that number
if(randomPick == 1)
{
location = spawn1;
Debug.Log("Chose pos 1");
}else if(randomPick == 2)
{
location = spawn2;
Debug.Log("Chose pos 2");
}
else if(randomPick == 3)
{
location = spawn3;
Debug.Log("Chose pos 3");
}
Rigidbody thingToMake;
//create the object at point of the location variable
thingToMake = (Rigidbody)Instantiate(prefab, location.position, location.rotation);
// move prefab with force
thingToMake.AddForce(new Vector3(100,100,100));
//halt script for 1 second before returning to the start of the process
yield return new WaitForSeconds(1);
//set spawning back to false so timer may start again
spawnEnem = false;
}
}