unity how to hold a reference to an object in a script code example
Example 1: reference to a gameobject
//refere a gameobject from the unity editor
Public GameObject ObjectName; //make sure this is public because you will need to assign it in the inspector
Void Start()
{
//lets say you want to disable the gameobject but want to enable later.
//you can do this a few ways, one of those ways is to use a bool, and the other is just to do it on the spot, we are going to do it on the spot.
ObjectName.SetActive(false); //this will disable the gameobject
}
//lets say you want to enable it through a fuction.
public void Yourfunction()
{
//you can start this function many ways, through a button, from another script or from this 1.
//we are going to do it from this 1.
ObjectName.SetActive(true);
}
//lets say if the player clicks 1 than it will get enabled.
public void Update()
{
if(Input.KetKeyDown("Alpha1"))
{
//this will check if the player clicks 1 if so it will call the function that sets the object to be enabled.
YourFunction();
}
}
Example 2: how to reference this gameobject unity
// use the keyword "this"
this.SetActive(true);
// the line above will set the GameObject this script is attached to active