I need a script that will create 3 different gameobjects at the start of the scene and also create new ones in random locations if a public variable is changed in the editor and the Spacebar is pressed. If the public variable is more than the private start values, it’ll make more but if the public variable is less, it won’t make anymore.
please help me, i’m still trying to learn all this coding stuff.
Pretty sure you need to be reading about instantiating, sounds like it won’t take you long.
I can spawn the objects just not in random locations
Have a look at Random.Range.
Thanks so much! How would I get the Y axis to randomize as well?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnObject : MonoBehaviour {
public GameObject cube;
public GameObject sphere;
public GameObject capsule;
// Use this for initialization
void Start() {
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.Space))
{
Vector3 cubePos = new Vector3(Random.Range(-5.0f, 5.0f), 0, Random.Range(-5.0f, 5.0f));
Instantiate(cube, cubePos, Quaternion.identity);
Vector3 spherePos = new Vector3(Random.Range(-5.0f, 5.0f), 0, Random.Range(-5.0f, 5.0f));
Instantiate(sphere, spherePos, Quaternion.identity);
Vector3 capsulePos = new Vector3(Random.Range(-5.0f, 5.0f), 0, Random.Range(-5.0f, 5.0f));
Instantiate(capsule, capsulePos, Quaternion.identity);
print(“SPACEBAR PRESSED!”);
}
}
}
You’re setting the Y axis to 0, instead just set it with Random.Range just like you are doing for the X and Z.