- Home /
(C#) Help with spawning a random GameObject
*Edited
Hello Unity community. I need help with spawning a gameobject.
So this is What I want to do. I want to have a random number choose 1 gameobject to spawn then I want to spawn just that One gameobject.
Here is my script *Edited
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(MobHealth))]
public class MobDrop : MonoBehaviour
{
public GameObject MobGameObject;
private int DropCounter = 0;
//Different things the mob can drop
public GameObject[] Drops;
public int RandomNumber;
//Get the MobHealth script
private MobHealth Mob;
void Start ()
{
Mob = MobGameObject.GetComponent<MobHealth>();
}
void Update ()
{
if(Mob.IsDead == true && DropCounter == 0)
{
DropTheMobDrop();
}
}
void DropTheMobDrop()
{
DropCounter ++;
RandomNumber = Random.Range(0,2);
var MobDrop = Instantiate(Drops[RandomNumber], new Vector3(transform.position.x, transform.position.y, 0.0f), Quaternion.identity) as GameObject;
MobDrop.name = Drops[RandomNumber].name;
}
}
this seems to work. Is it the best way to do it?
Thanks for any help :D
You've set up an infinite loop:
while(true) { ... }
Loops are usually used to make a thing happen more than once. If you want it to happen just once, why is it in a loop?
And if you get rid of the 'while' loop, I don't see any reason in the current code to make it a Coroutine. Change IEnumerator to void, and redo line 27 to be:
DropThe$$anonymous$$obDrop();
Also if I understand correctly what you are doing, you will need to reinitialize '$$anonymous$$ob' to the '$$anonymous$$obDrop', and you will need to change line 37 to:
var $$anonymous$$obDrop = Instantiate(Drops[RandomNumber], new Vector3(transform.position.x, transform.position.y, 0.0f), Quaternion.identity) as GameObject;
You don't despawn the mob anywhere, so every frame when Update is called it checks if the mob is dead, than it finds out it is and drops something.
I tired to make it despawn when it dies but that makes it not spawn anything.
There is a ton of confusing stuff going on here. Are you attaching this component to the mob? I see you are requiring $$anonymous$$obHealth, which would make sense. But then you are taking the $$anonymous$$obHealth component from another GameObject $$anonymous$$obGameObject. That's not going to work the way you expect.
Also.. you variable names should start with lower-case letters.
Answer by tebandesade · Jul 02, 2014 at 08:59 PM
Hi! You might want to check out http://docs.unity3d.com/Manual/RandomNumbers.html
Your answer
Follow this Question
Related Questions
How to make enemy prefab spawn at random times between 1.0f to 10.0f. 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Not repeating random 2 Answers
(C#)Place GameObject from Mouse 0 Answers