- Home /
Script crashing unity.
I'm trying to create asteroids that spawn from placed empty objects in the scene however the below script for which to instantiate them at random intervals is crashing the unity editor.
any clues as to why? and how I could solve this issue?
Code:
using UnityEngine;
using System.Collections;
public class asteroidBehaviour : MonoBehaviour {
public Rigidbody asteroid;
public float speed=1500f;
// Use this for initialization
void Start () {
SpawnAsteroid();
}
IEnumerator wait() {
yield return new WaitForSeconds(Random.Range(10.0f, 15.0f));
}
void SpawnAsteroid(){
while(true){
wait();
Rigidbody instance = Instantiate(asteroid, transform.position, transform.rotation) as Rigidbody;
transform.RotateAround(instance.position,Vector3.up, 20*Time.deltaTime);
Vector3 motion = transform.InverseTransformDirection(Vector3.forward);
instance.AddForce(motion *speed);
}
}
// Update is called once per frame
void Update () {
}
}
Thanks,
Euden
Answer by robertbu · Mar 15, 2013 at 04:17 AM
Here is a bit of rewriting of your code. Your main issue was how you were trying to use IEnumerator and yield:
using UnityEngine;
using System.Collections;
public class AsteroidBehaviour : MonoBehaviour {
public Rigidbody asteroid;
public float speed=1500f;
void Start () {
StartCoroutine(SpawnAsteroid());
}
IEnumerator SpawnAsteroid(){
while(true){
yield return new WaitForSeconds(Random.Range(10.0f, 15.0f));
Rigidbody instance = Instantiate(asteroid, transform.position, transform.rotation) as Rigidbody;
transform.RotateAround(instance.position,Vector3.up, 20*Time.deltaTime);
Vector3 motion = transform.InverseTransformDirection(Vector3.forward);
instance.AddForce(motion *speed);
}
}
}
Thanks! this solved my problem, is there a way to get the asteroids to rotate as they move, this seems to have stopped the rotation alltogether
Your answer
Follow this Question
Related Questions
Problem with spawning script 1 Answer
Instantiate 697283 trees by script? Crash! 2 Answers
Spawning a projectile with a trigger 1 Answer
Can't open script via Visual Studio (only last 2 days) 3 Answers