- Home /
String gives me Null,String gives me Null
Hi!! Im new to Unity and im working on inventory to my game. I have a GameObject for each slot and when you pickup an item it makes it an child Object where the parent is slot. I need to make the objects stack so when you pickup an item, script also takes sprite name of the object and stores it in a string. The thing is when i try to compare strings both of them give me Null. Look at it by yourself xD
int i = 0;
public SpriteRenderer sprite;
private GameObject objecth;
private Image sprite2;
string sprite3;
string sprite4;
void OnTriggerEnter2D(Collider2D other) {
if (other.CompareTag("Player")){
if (inventory.isFull[i] == false) {
objecth = Instantiate(itemButton, inventory.slots[i].transform, false);
sprite2 = objecth.GetComponent<Image>();
inventory.isFull[i] = true;
sprite3 = sprite2.sprite.name;
sprite4 = sprite.sprite.name.ToString();
Debug.Log(sprite3); //this gives me name of the sprite (thats correct)
Debug.Log(sprite4); //this gives me name of the sprite (thats correct too)
Destroy(gameObject);
}
else
{
Debug.Log(sprite4); //this gives me "Null"
Debug.Log(sprite3); //this gives me "Null" too
if(sprite4 == sprite3)
{
Instantiate(itemButton, inventory.slots[i].transform, false);
Destroy(gameObject);
}
else
{
i++;
}
}
}
Answer by logicandchaos · May 09, 2021 at 01:44 PM
It's simple the part where the strings are said to be null, they are null! You declare them at the start of the script, once declared a string's value will be null until it is assigned a value. You assign it a value here:
sprite3 = sprite2.sprite.name;
sprite4 = sprite.sprite.name.ToString();
But only if inventory.isFull[i] == false otherwise the value is never assigned, so when you go into the else clause the strings are undefined and so they are null.
The easiest way to fix this would be to assign a value when you declare it.
string sprite3="";
string sprite4="";
Now when you read it will be blank instead of null.
Hmm thats not bad idea but i dont need blank string, i need the values that i assigned in the if inventory.isFull[i] == false, is there a way to do it? ˇˇ thx for answer!
nvm figured it out, i just needed to make sprite3 static :D thx for answer anyway!
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Does unity C# support an exec method? 1 Answer
How to Instantiate from correct Icon. 1 Answer
Converting a string to an int 2 Answers