Hi there,
Im working on a runner game to familiarize myself with unity,
right now I have two spawn points tSpawn and bSpawn. Obstacles will spawn randomly on either of these two objects.
My goal is that I’m trying to translate them toward the player after instantiating so the player will have to jump over or duck under the obstacles.
Currently I have getting a NullReferenceException error on lines 37 and 43 (The lines that attempt to translate the Instances)
So the objects spawn, yet it tells me there is no reference to the objects?? so ofcourse if there’s no reference then no translation occurs, these obstacles just spawn and then don’t move.
My other question has to do with variable types.
“prefab” is of type GameObject, topInstance and BottomInstance are of type GameObject. Yet if I do not have “as GameObject” at the end of lines 36 and 42, then I get an error stating “cannot implicitly convert type from Object to GameObject.”
The funny thing is, “as GameObject” will get rid of this error, but type casting via (GameObject) does not, aren’t they supposed to do the same thing??
Anyway I mimicked this Instantiation code from
http://www.unity3dstudent.com/2010/07/beginner-b05-instantiate-to-create-objects/
Which is this below
//Simple Instantiation of a Prefab at Start
var thePrefab : GameObject;
function Start () {
var instance : GameObject = Instantiate(thePrefab, transform.position, transform.rotation);
I have the same thing as them, my prefab is a GameObject and so are my instances, but yet I get the error about implicitly converting. This doesn’t make sense!?
Here is my source below!
using UnityEngine;
using System.Collections;
public class ObstacleManager : MonoBehaviour
{
public GameObject tSpawn;
public GameObject bSpawn;
public GameObject prefab;
public float moveSpeed;
//private GameObject topInstance, bottomInstance;
//public float survivalTime;
// Use this for initialization
void Start ()
{
tSpawn = GameObject.Find("tSpawn");
bSpawn = GameObject.Find("bSpawn");
}
// Update is called once per frame
void Update ()
{
Spawn();
}
void Spawn()
{
GameObject topInstance, bottomInstance;
int[] choice = {0,1};
int topOrBottom = Random.Range(0, choice.Length);
Debug.Log("Choice :" + topOrBottom);
if(topOrBottom == 0)
{
Debug.Log("TOP Spawned");
topInstance = Instantiate(prefab, tSpawn.transform.position, tSpawn.transform.rotation) as GameObject;
topInstance.transform.Translate(-moveSpeed *Time.deltaTime, 0f, 0f);
}
else
{
Debug.Log("BOTTOM Spawned");
bottomInstance = Instantiate(prefab, bSpawn.transform.position, bSpawn.transform.rotation)as GameObject;
bottomInstance.transform.Translate(-moveSpeed * Time.deltaTime, 0f, 0f);
}
}
}
So essentially what im trying to do is Translate the objects toward the player.
In trying to do so, I ran into a few problems and raised some questions along the way.
This is probably a really simple fix, I’m so tired its 3 am here, probably the cause for my errors…
Thanks in advanced guys!