Hi, having trouble wrapping my head around achieving this:
I’m making a game where there are 4 spawn points on the right side of the screen.
I have an array of objects(1 in it at the moment)
I also have an array of spawnpoints (4)
My aim is to have the object move to the left side of the screen slowly until it reaches a trigger.
My current script is below.
My objects instantiate fine, and spawn in the right spots (grabs a random object from the “Junk” Gameobject array, spawns it in one of the 4 spawnpoints from the SpawnPoints Transform array.
How do I manipulate the spawned object to move in said motion?
I figure I need to make it a rigidbody, and use rigidbody.addforce, but i’m missing something!
The error message is:
SpawnItems.SpawnJunk() (Line 41): NullReferenceException: Object Reference not set to an instance of an object.
What am I forgetting to pass?
“JunkInstance.AddForce (SpawnPoints[spawnindex].forward * 800);”
Junkinstance is our instanced rigidbody. AddForce demands a vector3, Spawnpoints is our transform array, and spawnindex is a stored transform. .forward returns a vector3, so surely I’m not missing anything? 0_O. This isn’t making sense to me
using UnityEngine;
using System.Collections;
public class SpawnItems : MonoBehaviour {
// indexes Junk into an array
// indexes SpawnPoints into an array
// Spawns random Junk obj from a random SpawnPoint.
// Assign object to move down the lane it spawned in.
public Transform[] SpawnPoints; // array of spawnpoints, linked with transform in editor. this is also beginning of our "lanes".
public float SpawnTime = 1.5f; // time between spawn "waves"
public GameObject[] Junk; // Array of Junk Objects
// Use this for initialization
void Start () {
InvokeRepeating ("SpawnJunk", SpawnTime, SpawnTime);
// invokes SpawnJunk method after $SpawnTime seconds, then again every $SpawnTime seconds.
}
// Update is called once per frame
void Update () {
}
void SpawnJunk()
{
int spawnindex = Random.Range (0, SpawnPoints.Length);
// set index number of the array randomly
int objectIndex = Random.Range (0, Junk.Length);
// object Index = random number in range of between 0 & GameObject[] Junk.Length
Rigidbody JunkInstance;
JunkInstance = Instantiate (Junk[objectIndex], SpawnPoints [spawnindex].position, SpawnPoints [spawnindex].rotation) as Rigidbody;
// Instantiates a random Junk obj to a random spawnpoint, following the spawnpoint's rotation.
JunkInstance.AddForce (SpawnPoints[spawnindex].forward * 800);
// BROKEN!
}
}