首页 > 解决方案 > How to get reference to GameObject without using Find() in C#/Unity?

问题描述

I am currently taking an intro to games programming class and in the lecture notes it mentions that instead of using something like:

GameObject obj = GameObject.Find("name");

inside functions, you can "add object as Public member of type GameObject and connect it in the inspector" without actually explaining how to do it.

I tried to lookup how to do this but was unable to find how to properly do so, would appreciate any help.

标签: c#unity3d

解决方案


Here is how you could do it. Lets say you want obj2 in obj1

First go in the script of obj1 and declare a public variable public GameObject obj2;

Then go in to the inspector of the obj1, on script component you will find a field Obj2. Now just drag and drop the obj2 from hierarchy in that field or click a circular button next to field and select the object from the list.


推荐阅读