Reputation: 113
I am having trouble getting one script to call an instantiation function from another script. The following image illustrates how I have my game objects set up.
I have 2 object things, Thing1 and Thing2, which move around the screen based on a movement script that is attached to each of them. Thing1 also has attached a reaction script. When Thing1 and Thing2 collide, Thing 3 should appear. Thing3 has an instantiation script attached to it that contains a function with an instantiation command.
When I call the instantiation function within the instantiation script (I put it in the Start function of Thing3), it works fine. However, when I take it out of there and try to put it in the Start function of the reaction script attached to Thing2 I cannot get it to work. Most currently, I get no error on compiling but as soon as the game starts I get is the following (The behavior of Thing1 and Thing2 also seems to be adversely affected):
"NullReferenceException: Object reference not set to an instance of an object"
When I look up the reason for that error I find that the most typical reason for that is a prefab object not being attached to the script. However, I DO have a prefab attached to the script. It is attached to the instantiation script that contains the instantiation function.
Below is the code for the instantiation script and the reaction script that is calling the instantiation function within the instatiation script.
//Instantiation
public class Thing3Instantiation : MonoBehaviour
{
public GameObject thing3Obj;
void Start()
{
//CreateThing3();
}
public void CreateThing3()
{
Instantiate(thing3Obj);
}
}
And
//Reaction
public class Reaction : MonoBehaviour
{
private Thing3Instatiation thing3instantiation;
void Awake()
{
thing3instantiation = GetComponent<Thing3Instantiation>();
}
void Start()
{
thing3instantiation.CreateThing3(); //This line triggers the null error
}
Any ideas on what I'm doing wrong?
Upvotes: 0
Views: 696
Reputation: 364
If I understand your setup correctly:
So when Reaction awakes, it tries to find the component called Thing3Instantiation on its own gameObject (Thing1). But it isn't on Thing1 it is on Thing3, so GetComponent
returns null
.
Hence, your NullReferenceException.
Upvotes: 2
Reputation: 335
Your problem is actually at the line of Instantiate(thing3Obj);
.
In other words... When you Instantiate a script, you won't have variables assigned, in your case thing3Obj
. No matter if you've assigned them through Inspector, when Instanciated, you get a clean copy of that class, unallocated. You need to assign it before calling, that's why it's giving the Null exception.
Upvotes: 1