I have a script working at the open of a level called OnGameStart. Its fine.
However I want to give this script control over the appearance of certain GameObjects.
For example, I want it to turn off some gameobjects so the user doesn’t see them until some unrelated tweens play and stuff happens.
I am having trouble causing the script to recognize what object it needs to manipulate and what it can do with that object.
Here’s what I have related to my desired functionality:
An object in my Hierarchy called HeroPowerButton – two of them are in the scene. I want these to appear in the scene only after certain starting sequences.
...........
public HeroPowerButton playerHeroPowerButtons;
...........
In OnGameStart()
playerHeroPowerButtons.SetActive(false);
Invoke("TurnOnHeroPowerButtons", 3f);
...............
private void TurnOnHeroPowerButtons()
{
playerHeroPowerButtons.SetActive(true);
}
I can’t get it to compile because “HeroPowerButton does not contain a definition for SetActive”. I thought every gameobject understood SetActive.
Am I not supposed to give my GameObject HeroPowerButton the name playerHeroPowerButtons and then use the new name I gave it for the GameObject’s manipulation?
I appreciate you reading & help on wrapping my head around how scripts can work with gameobjects.
You need to do
playerHeroPowerButtons.gameObject.SetActive(false);
You have to target the gameObject if you link it by script, otherwise, there is no way of knowing this is a GameObject. As you declared it, it’s a reference to an instance of the script.
For anyone having trouble Linking Objects From Hierarchy To Public Fields In Unity’s Inspector here’s one solution:
When the script compiled, I noticed I could not drag and link the gameobject(s) in the scene called HeroPowerButton(s) from the Hierarchy to the inspector field “player Hero Power Buttons” variable I declared in my script with the HeroButtonPower:
"public HeroButtonPower playerHeroPowerButtons".
I changed the declaration to
public GameObject playerHeroPowerButton1
public GameObject playerHeroPowerButton2
and it works like a charm altogether.
by the way what is that 2nd field in the variable called? Is it Type GameObject I declared properly instead of Type HeroButtonPower?
Well, variables have a type. So GameObject is the type and you can tie any gameobject to that variable. If you declare as a HeroButtonPower type, then you have to have a gameobject with that script on it and then you can attach that gameObject to that variable as it has an instance to that script on it.
Which type you use depends on what you plan to do with it. If you use the script, then you don’t have to use GetComponent to access the script on the gameObject as you already have a reference to it. I generally prefer this as I can then just use the .gameObject to get to the gameObject the script is attached to.
variables are declared (for the basic variable)
accessor type variableName