通过另一个脚本分配脚本的gameObject?

时间:2020-03-18 13:28:40

标签: c# unity3d

如何通过另一个脚本的gameObject分配一个脚本的gameObject?例如; 脚本_1

public class Script_1 : MonoBehaviour
{
    public OVRScript OVR;
}

脚本_2

public class Script_2 : MonoBehaviour
{
    private Script_1 src_1;
    public GameObject Front;

  void Start()
    {
        src_1 = (Script_1) GameObject.FindObjectOfType(typeof(Script_1));
        src_1.GetComponent<OVRScript >().OVR = Front //I am facing problem here
    }

}

GameObjects“ OVR”和“ Front”都包含OVRScript

2 个答案:

答案 0 :(得分:1)

src_1.GetComponent<OVRScript>().OVR = Front.GetComponent<OVRScript>().OVR;

答案 1 :(得分:0)

我不知道或没有看到OVRScript类,但是OVR不是Script_1的成员吗?

然后您想在Front上使用GetComponent以便将组件连接到它。

// If possible rather drag your Script_1 in here directly via the Inspector
[SeializeField] private Script_1 src_1;

void Start()
{
    // Now I would use find only as fallback
    if(!scr_1) src_1 = GameObject.FindObjectOfType<Script_1>();

    // then you want to assign the OVR field of the 'src_1' of type 'Script_1'
    // and not use 'src_1.GetComponent<OVRScript>()' which would return
    // the reference of an 'OVRScript' component attached to the same GameObject as the Script_1
    //
    // And you want to fill it with the reference of an 'OVRScript' attached to 'Front'
    src_1.OVR = Front.GetComponent<OVRScript>();
}

(请参见[SerializeField]


直接定义会更好

public OVRScript Front;

现在,如果您拖动GameObject,则a)检查此GameObject是否实际附加了OVRScript,否则不能删除它,并且b)代替{ {1}}个引用已经被GameObject引用序列化并存储,因此不再需要OVRScript

GetComponent
相关问题