- Home /
How to give a speed to random spawned object?
Hi, how can I give a speed to random spawned object. I have this script:
using UnityEngine;
using System.Collections;
public class Spawner : MonoBehaviour
{
public float spawnTime = 5f; // The amount of time between each spawn.
public float spawnDelay = 3f; // The amount of time before spawning starts.
public GameObject[] baloon2; // Array of enemy prefabs.
void Start ()
{
// Start calling the Spawn function repeatedly after a delay .
InvokeRepeating("Spawn", spawnDelay, spawnTime);
}
void Spawn ()
{
// Instantiate a random enemy.
int enemyIndex = Random.Range(0, baloon2.Length);
Instantiate(baloon2[enemyIndex], transform.position, transform.rotation);
// Play the spawning effect from all of the particle systems.
foreach(ParticleSystem p in GetComponentsInChildren<ParticleSystem>())
{
p.Play();
}
}
}
This script works fine but objects are spawning but not moving. How can I apply speed to them?
Comment
Best Answer
Answer by robertbu · Jan 17, 2014 at 05:53 PM
Not sure what direction you want them to move. Given the name 'baloon2', maybe up?
Replace 22 with:
var go = Instantiate(baloon2[enemyIndex], transform.position, transform.rotation) as GameObject;
go.rigidbody.AddForce(Vector3.up * someForce);
With a Rigidbody.mass of 1.0, start with 'someForce' at 500 and adjust from there.
I misspelled balloon name so baloon2 is actually ok. I get error saying that there is no definition for AddForce