- Home /
Question by
ironictrout · May 30, 2018 at 10:58 PM ·
gameobjecttransformnullreferenceexception
Trying to call a function from a dynamically created object
I have this bare-bones version of another script that is making a planet. I am using this script in another class called solar system to make a bunch of planets. I have created a method for moving the planets that I can call dynamically later to update their positions. Whenever I try and call it I am getting a NullReferenceException saying: Object reference not set to an instance of an object.
Here is the planet class:
public class planet_test : MonoBehaviour {
public GameObject planet_controller;
// Use this for initialization
void Start () {
planet_controller = new GameObject ();
}
// Update is called once per frame
void Update () {
}
public void movePlanet(float x, float y, float z){
planet_controller.transform.position = new Vector3 (x, y, z);
}
}
And here is the solar system class:
public class solare_system_test : MonoBehaviour {
// Use this for initialization
void Start () {
GameObject planet = new GameObject ();
planet.AddComponent<planet_test> ();
planet.GetComponent<planet_test>().movePlanet(50f, 0f, 0f);
}
// Update is called once per frame
void Update () {
}
}
Comment
Best Answer
Answer by b1gry4n · May 31, 2018 at 12:00 AM
You are trying to move a null object. "planet_test" script is not given the opportunity to start before you try to tell it to move.
public class solare_system_test : MonoBehaviour
{
// Use this for initialization
void Start()
{
GameObject planet = new GameObject();
planet_test pt = planet.AddComponent<planet_test>();
pt.Initialize();
pt.movePlanet(50f, 0f, 0f);
}
}
public class planet_test : MonoBehaviour
{
public GameObject planet_controller;
// Use this for initialization
public void Initialize()
{
planet_controller = new GameObject();
}
public void movePlanet(float x, float y, float z)
{
planet_controller.transform.position = new Vector3(x, y, z);
}
}