I’m having trouble with creating a script in C# that does what the title says, Instantiate objects at a random time between a random range.
I need to spawn spheres at a random time range such as between 1-4 seconds in a random transform range such as X (14, 15).
I was going to do something along the lines of this below in C# and then calling the function(void in C#) when the spheres collide with barriers I put in place outside of the camera. But not sure how to clamp the random time spawn as well as instantiating them in those random.range’s.
function ResetBall()
{
//Resets position
transform.position.x = Random.Range(13,-13);
transform.position.y = Random.Range(14,15);
}
I’m sorry but maybe I’m missing it in the code or I didn’t explain it enough.
I’m trying to spawn a sphere at a random time in a random range for coords. I would then like to call the ResetBall (+ the random time part) function once the sphere collides with my barrier in order to save performance.
So it would be something along the lines of the below code:
void OnTriggerEnter ( Collider other ){
if(other.gameObject.tag == "OutOfBounds")
{
ResetBall();
}
}
void ResetBall (){
transform.position.x = Random.Range(13,-13);
transform.position.y = Random.Range(19,19);
//+ the yield WaitForSeconds part
}
the need to instantiate the sphere, which I can’t remember how to do in C# :S I’ve been using Java a ton but now I’m switching to C#.
So I’d like to use my prefab sphere and then instantiate it, once is goes “OutOfBounds” do the random range respawn and time delay. But not sure how to make that one script? Unless it needs to be 2.
Either your ball is in the scene already and your game play stays in that scene then you don’t need to care about instantiating. Most often you will have for example a variable number of balls. In these cases you might want to have a spawner class in your scene:
public class Spawner {
public GameObject ballPrefab;
void Start () {
GameObject ball = Instantiate (ballPrefab) as GameObject;
}
}
Error is “Cannot modify a value type return value of `UnityEngine.Transform.position’. Consider storing the value in a temporary variable”.
As you could imagine the error is on the transform.position.x and y lines.