- Home /
Random cube length on instantiate...
One of the GameObjects I am using in my game are cubes... But my game depends on cubes being of random lengths, almost like platforms, because my game is a FallDown clone where you have to keep going down or lose. I have a script that generates cubes and spawns them at random coordinates (included below). I also have a cube prefab, which is a generic cube to be spawned. I was thinking, maybe the way to do this is not through a prefab, but through another method I am not aware of.
When the cubes spawn, they move upwards due to directional gravity, giving the illusion of descending.
SCRIPT:
using UnityEngine;
using System.Collections;
public class GOSpawn : MonoBehaviour {
public float delay;
public GameObject thingy;
// Use this for initialization
void Start () {
InvokeRepeating("Spawn", delay, delay);
}
// Update is called once per frame
void Spawn () {
Instantiate(thingy, new Vector3(Random.Range(-6, 6), 10, 0), Quaternion.identity);
}
}
C# plezzz thanks (in advance) :D
Answer by clunk47 · Feb 17, 2014 at 07:11 PM
When you Instantiate, create a new instance of your prefab, or "clone" your "thingy" gameObject. Then create a Vector3 scale that caches the original scale of the clone. Next, change the scale variable on the desired axis or axes, then set your clone's localScale to the new scale setting.
using UnityEngine;
using System.Collections;
public class GOSpawn : MonoBehaviour
{
public float delay;
public GameObject thingy;
void Start ()
{
InvokeRepeating("Spawn", delay, delay);
}
void Spawn ()
{
GameObject thingy_clone = Instantiate(thingy, new Vector3(Random.Range(-6, 6), 10, 0), Quaternion.identity) as GameObject;
Vector3 scale = thingy_clone.transform.localScale;
scale.x = Random.Range (1, 4);
thingy_clone.transform.localScale = scale;
}
}
I have to tag @Vexe in this because you made me say "Clone your thingy" lol.
Jesus Christ :D
I'll see into cloning my "thingy" later... however thanks so much, I am always getting perfect help from you :D
Note I changed to a cast using "as" ins$$anonymous$$d of using a direct cast, Vexe kinda gave me some advice on that. http://stackoverflow.com/questions/132445/direct-casting-vs-as-operator
How relevant it is that we are talking about cloning "thingies", Vexe has 169 answers on his profile... 169... 69... shit.
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Spawing a SpawnPoint with Raycast 0 Answers
Random Spawning 1 Answer
Procedural Spawning Theorems 0 Answers
Respawn after falling off script? 2 Answers