Hello!
I am fairly new to programming and was looking for some help with my spawning script. Right now this script spawns my “points” in a random range in the designated area, which is exactly what I want it to do. My problem comes when the point spawns in of the GameObjects on the level. I understand the logic of what I want to happen but all my attempts have failed.
What I want is some form of “point spawn check” that checks a spot, if it’s touching an object with a tag or layer “obstacle,” do not spawn and pick a new spot. I have an empty game object that moves around the scene and determines where the point will spawn. My “Generator” script is attached to this object.
I want to use the “Physics.OverlapSphere” and attach a physics sphere on the game object with the Generator script, set the obstacles in the level to a specific layer and have it check for this layer before spawning.
When you look at the script you can see I sorta tried to figure it out the the “groundCheck and whatIsGround” stuff but I couldn’t get it to work.
Ill post my script below if you need more info or scripts please tell me, any help would be greatly appreciated!
public class Generator : MonoBehaviour
{
public Transform pointDrop;
public int numToSpawn;
public Vector3 position;
public bool pointSpawned = false;
public float pointTime = 5.0f;
bool goodSpot = false;
bool badSpot = false;
public bool waiting = false;
bool grounded = false;
public Transform groundCheck;
float groundRadius = 5f;
public LayerMask whatIsGround;
void SpawnPoint()
{
pointSpawned = true;
Instantiate(pointDrop, position, pointDrop.transform.rotation);
}
public void Hit()
{
StartCoroutine(Wait(2f));
waiting = true;
}
public void Miss()
{
pointSpawned = false;
}
IEnumerator Wait(float waitTime)
{
yield return new WaitForSeconds(waitTime);
//Debug.Log("Wait is finished");
waiting = false;
pointSpawned = false;
StopCoroutine(Wait(waitTime));
}
void FixedUpdate()
{
groundCheck = transform.Find("GroundCheck");
grounded = Physics2D.OverlapCircle(groundCheck.position,groundRadius,whatIsGround);
}
void Update()
{
int spawned = 0;
if(pointSpawned == false)
{
if(grounded)
{
goodSpot = true;
badSpot = false;
}
}
if(!grounded)
{
badSpot = true;
goodSpot = false;
//pointSpawned = false;
}
if(pointSpawned == false)
{
position = new Vector3(Random.Range(-7.25f, 8.9f), -.3f, Random.Range(5.66f, -3.1f));
transform.position = position;
if(!gameObject.CompareTag("obstacle"))
{
spawned++;
SpawnPoint();
}
//if(badSpot == true)
//{
// ResetTimer();
// pointSpawned = false;
//}
}
/*
//Good code
pointTime -= Time.deltaTime;
if(pointTime <= 0.0f)
{
pointSpawned = false;
ResetTimer();
}
*/
}
void ResetTimer()
{
pointTime = 5.0f;
}
}