- Home /
Reference a instantiated object?
So i have a question, heres some code.
if(equipped == true){
}else if(equipped == false){
GameObject item = (GameObject)Instantiate(inventory[selected], transform.parent.position, transform.parent.rotation) as GameObject;
}
So now lets say i would like to acess the instantiated game object in the else if statement, How do i go about doing that? I've looked through some documentation but i cannot figure out how.
Im sorry im not getting it. you said you want to access gameObject in "else if" and you are actually accessing it in "else if". Do you want to say outside of else if? Or something else...?
@Yash I would like to acess the instantiated object that resides in the if statement.
In example there is nothing inside if statement :( $$anonymous$$eeping a reference outside of if else structure will work if you want to have same reference for something you instantiate in either if or in else if.
Answer by _Yash_ · Oct 25, 2014 at 06:17 PM
Finally I got what you are trying to say. inside "if" you can do
1) GameObject.Find() to get already equipped object. Change the name of object to something specific so that you can find it with it's name.
2) you can have Global reference to an GameObject and just access it inside if and change it when you instantiate inside else if.
Answer by AlwaysSunny · Oct 25, 2014 at 05:56 PM
if(equipped){
// do this
}else{
// removed implicit cast, not necessary when "as" casting
GameObject item = Instantiate(inventory[selected], transform.parent.position, transform.parent.rotation) as GameObject;
// access instantiated object using variable to which you assigned it
item.name = "SomeName";
DoStuff(item);
}
I knew how to do this but lets say if the player hasnt equipped the item, then we instantiate the object, but if equipped = true then we want to reference the instantiated object? i cant seem to make it work in other statement
In that case, like @Yash said, declare the "item" variable outside of the if/else block. You don't have to assign to it when declaring, in which case it'll be null, so you'll have to check whether it's null before trying to do anything besides assignment.