Reputation: 516
Being a student and having finished my school year I studied the development of Unity in C # to learn how to use the engine but also and above all to have fun.
One of the advantages of Unity is that you can pass a game object parameter directly in drag/drop, but for this to be possible it is necessary that the said variable is in public, which goes against what I have learned in class (the attributes must be private as often as possible).
My question was, how to make sure to have the same result with private attributes, i.e., recovered the game object manually without using the drag/drop system?
Thanks in advance and sorry for my English level.
Upvotes: 3
Views: 853
Reputation: 125245
It is not necessary to mark the variable as public
in order to make it appear in the Editor. Just just put the SerializeField
attribute on top of the private
variable and it should show up in the Editor.
[SerializeField]
private GameObject cam1;
You can also do the opposite which is make public
variable not show in the Editor. This can be done with the HideInInspector
attribute.
[HideInInspector]
public GameObject cam1;
But there is another method in Unity to get a GameObject, by avoiding drag/drop ?
Yes. Many ways.
If the GameObject already exist in the scene then You can with one of the GameObject.FindXXX
functions such as GameObject.Find
, GameObject.FindGameObjectWithTag
For example,
[HideInInspector]
public GameObject cam1;
// Use this for initialization
void Start()
{
cam1 = GameObject.Find("Name of GameObject");
}
If the GameObject is just a prefab then put the prefab in a folder named Resources then use Resources.Load
to load it. See this for more thorough examples.
Finally if you just want to get the component of that GameObject, just like your cam1
variable which is not a GameObject but a component, First, find the GameObject like I did above then use the GetComponent
function to get the component from it.
private Camera cam1;
// Use this for initialization
void Start()
{
GameObject obj = GameObject.Find("Main Camera");
cam1 = obj.GetComponent<Camera>();
}
Upvotes: 9