- Home /
String Variable From External Script Set To Null?
Alright, so I'm making a BreakOut clone. I'm working on the collision between a powerup and the paddle. The powerup has a global string 'type', which decides the type of powerup. It gets assigned after instantiating the powerup. Thing is, when I access this variable through the OnCollisionEnter in the paddle script, it becomes null, tested with a print. However, if I print the variable after instantiating the powerup, it isn't set to null. Can anyone clear this up for me? This is my code for the script on the paddle object:
void OnCollisionEnter(Collision other)
{
if (other.gameObject.tag == "powerup")
{
if (other.gameObject.GetComponent<PowerUp>().type == "Wide")
{
print ("Wide PU!");
}
else if (other.gameObject.GetComponent<PowerUp>().type == "Split")
{
print ("Split PU!");
}
//Only the Else gets executed: the print() only displays 'Type: ', indicating the 'type' variable is null?
else print("Type: " + other.gameObject.GetComponent<PowerUp>().type);
Destroy(other.gameObject);
}
}
This is my code for the script on the PowerUp object:
public string type;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
//This function acts as a class constructor.
//It may be called after Initializing this GameObject to set proper Power Up behavior.
public void Initialize(string type)
{
//Test the type string given when a brick breaks in BrickBreak script
switch (type)
{
case "Wide":
//If the type is 'wide', set proper graphical and logical settings
renderer.material.color = Color.red;
type = "Wide";
print ("Spawn Type: " + type); //This displays the type variable just fine!
break;
case "Split":
renderer.material.color = Color.green;
type = "Split";
print ("Spawn Type: " + type); //This displays the type variable just fine!
break;
default:
print ("No proper Power Up constructor string input!");
break;
}
}
Answer by turbosheep · Jan 04, 2015 at 12:40 PM
Alright, did not find out why the variable got set to null somehow, but moving some code to the PowerUp script's Awake() fixed it for now.
Answer by Ekta-Mehta-D · Jan 03, 2015 at 12:43 PM
Hii ..
Try to assign string to variable type from Inspector . And check still u r getting null.
I feel like this could be the issue. Of course, the field of 'type' in the inspector is empty, since the public variable only gets assigned a string when the object is created. I wonder, why doesn't this field get a value when the object gets created and a value is assigned?
You need to call Initialize in Start(). Then that variable get assigned.
I could try that, but it leaves me confused. The Initialize function gets called way before the paddle collides with it and checks for its type. When the Initialize function gets called, it prints the type, this proves Initialize got called in time! Why is the type variable suddenly empty when I call it later on through a OnCollisionEnter from the paddle? I don't get the logic.