Are they supposed to be off screen in the Y- or X-axis? Since you’re using transform.position.y as the start position, the thing that the script is attached to must be off screen in the Y-axis. If so, something like this might help:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class Gamecontroller : MonoBehaviour {
public Camera cam;
public GameObject ball;
private float maxWidth;
private float maxHeight;
public Text timerText;
public float timeLeft;
// Use this for initialization
void Start () {
if (cam == null) {
cam = Camera.main;
}
Vector3 upperCorner = new Vector3 (Screen.width, Screen.height, 0.0f);
Vector3 targetWidth = cam.ScreenToWorldPoint (upperCorner);
float ballWidth = ball.renderer.bounds.extents.x;
float ballHeight = ball.renderer.bounds.extents.y;
maxWidth = targetWidth.x - ballWidth;
maxHeight = targetWidth.y + ballHeight;
StartCoroutine (Spawn());
}
void FixedUpdate(){
timeLeft -= Time.deltaTime;
if (timeLeft < 0) {
timeLeft = 0;
}
timerText.text = "Time left:\n" + Mathf.RoundToInt (timeLeft);
}
IEnumerator Spawn () {
yield return new WaitForSeconds (2.0f);
while (timeLeft > 0) {
Vector3 spawnPosition = new Vector3 (
transform.position.x + Random.Range (-maxWidth, maxWidth),
transform.position.y + maxHeight,
0.0f
);
Quaternion spawnRotation = Quaternion.identity;
Instantiate (ball, spawnPosition, spawnRotation);
yield return new WaitForSeconds (Random.Range (1.0f, 2.0f));
}
}
}
Where is the object you attach the script to located? Is it in the center of the screen? The script will only work if that is the case. I’ve tried it and it works as intended.
Also, I had a small error in the script. Change:
maxHeight = targetHeight.y + ballHeight;
to:
maxHeight = targetWidth.y + ballHeight;
Sorry for that… I’ve edited my previous reply with that change.