Instantiated in IF statement - Else Reference object
Im extremely new to programming so bear with me.
public void clickWood()
{
//Check If The Player Has Gotten Wood Previously
if(_hasWood == false)
{
GameObject newItem = Instantiate(wood_prefab) as GameObject;
//Initial Displayed Name
newItem.GetComponent<ButtonSetter>().setName("WOOD: ");
//Starts with 0 Wood, set to 1
newItem.GetComponent<ButtonSetter>().item_count += 1;
newItem.transform.SetParent(GameObject.Find("Content").transform,false);
//Got their first wood, should run else from now on
_hasWood = true;
}
else
{
//SEE CONTINUED POST
}
}
So, within the else statement, I want to basically say,
They got their first wood, so we created a panel to display information about the wood they have. Now I want to say, since we have already instantiated the displayPanel, we just want to work from that and adjust the object's variable that controls the integer part of "Wood: 0"
This should be
newItem.GetComponent<ButtonSetter>().item_count
But if I try accessing that within the else statement as shown:
newItem.GetComponent<ButtonSetter>().item_count += 1;
It tells me that newItem does not exist within the current context. How can I Instantiate something under certain conditions, then after the condition was met, take the instantiated object and work with its script/variables?
Here is a Visual Representation of my question
Answer by Hellium · Nov 28, 2018 at 04:36 PM
public ButtonSetter WoodPrefab;
private ButtonSetter woodItem;
public void clickWood()
{
//Check If The Player Has Gotten Wood Previously
if( woodItem == null )
{
woodItem = Instantiate(WoodPrefab);
woodItem.transform.SetParent(GameObject.Find("Content").transform,false);
//Initial Displayed Name
woodItem.setName("WOOD: ");
}
woodItem.item_count++;
}
Your answer
Follow this Question
Related Questions
List becomes empty when accessed in another class 0 Answers
How to make an Inventory Hotbar (C#) 0 Answers
How to create an if statement for each element within a list C# 2 Answers
Unity Dropdown Menu Not Closing 1 Answer
GUI Label not showing up on Android device while works perfectly in Unity 0 Answers