- Home /
Instantiating a GameObject from scene that changes
So I'm currently trying to instantiate a game object in a scene every few seconds, and that object is constantly changing. I tried linking it as a public variable to the script, but I keep getting null reference exceptions. any idea why this code is unable to spawn the GameObject wall?
using UnityEngine;
using System.Collections;
public class BPMController : MonoBehaviour {
public int bpm;
public GameObject wall;
public GameObject floor;
bool wait = false;
int spawnCounter = 0;
public int spawnInterval = 4;
//find the wall in the scene
void Start () {
wall = GameObject.FindGameObjectWithTag("wall");
}
void Update () {
//if coroutine isnt running start it
if (!wait)
{
wait = true;
StartCoroutine(waitCoRoutine());
}
//if interval count is reached, spawn wall
if(spawnCounter >= spawnInterval)
{
spawnWall();
spawnCounter = 0;
}
}
//coroutine to wait a set time and increment counter
IEnumerator waitCoRoutine(){
yield return new WaitForSeconds(bpm/60);
spawnCounter++;
wait = false;
}
void spawnWall(){
//create cloneObject to manipulate
GameObject wallClone = null;
//instantiate wallCone as a clone of wall
wallClone = Instantiate (wall, wall.transform.position, wallClone.transform.rotation) as GameObject;
//set wallcone as a child of floor;
wallClone.transform.parent = floor.transform;
}
}
Answer by RudyTheDev · Feb 14, 2014 at 05:44 PM
In the line
wallClone = Instantiate (wall, wall.transform.position, wallClone.transform.rotation) as GameObject;
you have wallClone.transform.rotation
before you have wallClone
assigned. I'm guessing this is where your null exception happens, since you didn't specify the exact line.
If it's not, then either your public GameObject wall;
is getting destroyed at some point or your wall = GameObject.FindGameObjectWithTag("wall");
has failed to find it to begin with.
your my hero. I coded this at 4am last night and somehow never noticed it said wallClone in the instantiate. thanks for that
Don't forget to mark the answer as accepted if this resolves your issue.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
How to not instantiate an object if there is another object there? 1 Answer
MonoBehavior.Start() called infinite times? 1 Answer
Instantiated Prefab doesn't find main camera 2 Answers
How can I check if an instantiated object collides with another instantiated object? 1 Answer