- Home /
Can you compare a Gameobject to a Variable?
I'm working on an inventory system, and I am very close to being able to click an active slot, destroy the object already there, and then place the new object. The thing is, I am using scriptable objects to make the inventory system because I want a system that I can just make a scriptable object and then it works without any other input needed. I can't seem to get the active GameObject to link up with the variable on the scriptable object so then I can get the GameObject on the scriptable object that the image is sitting on. I'm sorry if you don't understand, but its hard to explain. I have the code to look at though on the bottom. I basically go through a loop looking for if the image is the same as the S.O. with the variable of i for the duration of the amount of items(scriptable objects) I have. The main part I need help with is the if statement in the for loop. If you could help that would be great. Thanks!
public void EquipItem(Button clicked)
{
if (clicked.gameObject.transform.childCount == 1)
{
Destroy(currentOBJ);
for (int i = 0; i < items.Length; i++)
{
if (GameObject.ReferenceEquals(items[i].itemSprite, clicked.transform.GetChild(0)))
{
currentOBJ = Instantiate(items[i].itemObj, hand.transform.position, hand.transform.rotation);
currentOBJ.transform.parent = hand.transform;
break;
}
}
}
else
{
Debug.LogError("No child");
}
}
I never used ReferenceEquals before, but it seems to be used to compare 2 gameObjects. you want to compare 2 sprites, you should be able to just use = like this:
if (items[i].itemSprite == clicked.transform.GetChild(0).sprite)
assu$$anonymous$$g itemSprite is a sprite and GetChild(0).sprite is valid.
Answer by ahstein · Apr 03, 2021 at 05:28 PM
It appears that you're trying to compare a GameObject to a sprite? Is that correct?
A GameObject on its own doesn't have any real properties to compare to. You want to use GetComponent to find the component that has the property you actually want to compare to. For example:
SpriteRenderer sr = myGameObject.GetComponent<SpriteRenderer>();
if(sr.sprite == mySprite)
{
Debug.Log("They match!");
}
Answer by unity_zgZIxccP2cRekQ · Apr 03, 2021 at 09:55 PM
@ahstein , thanks so much. I don't know why i didn't realize, but again thank you. All I changed was instead look for the same sprite that the two share. Thanks again!!!!
Your answer
Follow this Question
Related Questions
Getting Scriptable object variables from a loop., 1 Answer
Scrolling combat text works on enemy. When I duplicate and have two enemies I get a problem. 1 Answer
Adding listeners to a button with a temp variable isn't working 0 Answers
ScriptableObject reference resetted after a method is finished. 2 Answers
Get data from Server 0 Answers