Random Spawn objects within the Screen (width and height) area

Hi guys, I created the cube and it is random spawning, but when the first cube is created, it does not appear inside the screen. What I want is the cube will be spawn randomly inside the screen (width and height) area. How could I do that?

Here is the code:

using UnityEngine;
using System.Collections;

public class ObjectsCreation : MonoBehaviour 
{
    public GameObject gameObject;

    public float timer = 0.0f;

	// Use this for initialization
	void Start () 
    {
	    
	}
	
	// Update is called once per frame
	void Update () 
    {
        timer += Time.deltaTime;

        if (timer > Random.Range(3, 5))
        {
            bool called = Instantiate(gameObject, new Vector3(Random.Range(Screen.width / 2, Screen.width), Random.Range(Screen.height / 2, Screen.height), 0), Quaternion.identity) as GameObject;

            if (called)
            {
                Debug.Log("Object has been created, timer reset");
            }

            timer = 0.0f;
        }
	}
}

Thanks in advance!

If it is one layer, then you are talking about a fixed distance from the camera. This would probably be done easier using a Coroutine, but here are some changes within the framework of your code.

Some notes:

  • Don’t use ‘gameObject’ for a variable name. ‘gameObject’ refers to the game object on which the script is attached.
  • You don’t want to call Random.Range() every frame to do your check. You want to call it once per cycle.
  • While you could use screen coordinates for the random and then convert to world coordinates, it is easier to use Viewport coordinates. They go form 0 to 1 both height and width of the screen.
  • ‘distFromCamera’ is the distance from the camera plane to the layer of objects you are creating.

using UnityEngine;
using System.Collections;

public class ObjectsCreation : MonoBehaviour 
{
	public GameObject prefab;

	public float minSpawnTime = 3.0f;
	public float maxSpawnTime = 5.0f;
	public float distFromCamera = 10.0f;

	private float timer = 0.0f;
	private float nextTime;
		
	void Start () {
		nextTime = Random.Range(minSpawnTime, maxSpawnTime);	
	}
	
	void Update () {
		timer += Time.deltaTime;
		
		if (timer > nextTime) {
			Vector3 pos = new Vector3(Random.value, Random.value, distFromCamera);
			pos = Camera.main.ViewportToWorldPoint(pos);

			Instantiate(prefab, pos, Quaternion.identity);
            
			Debug.Log("Object created");
			
			timer = 0.0f;
			nextTime = Random.Range(minSpawnTime, maxSpawnTime);
		}
	}
}