从另一个脚本访问组件

时间:2019-04-01 13:36:17

标签: unity3d

我正在使用统一性,我正在尝试访问父对象上名为Outline的脚本。我需要从另一个名为Outline的脚本中禁用和启用脚本Destroyable。我知道那里有大量的教程和其他问题,但似乎总是找不到。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Destroyable : MonoBehaviour
{
    Outline myScript;
    private void OnMouseDown()
    {
        Destroy(gameObject);
    }

    // Start is called before the first frame update
    private void Start()
    {
        myScript = gameObject.GetComponent<Outline>();
    }

    // Update is called once per frame
    void Update()
    {

    }
}

2 个答案:

答案 0 :(得分:1)

如果它们与同一对象

myScript = GetComponent<Outline>();

应该已经为您提供了想要的参考。

否则,如果您说它在父对象上,则应改用

myScript = transform.parent.GetComponent<Outline>();

GetComponentInParent(仅在启用该组件且GameObject在“开始”时处于活动状态)

myScript = GetComponentInParent<Outline>();

更好(如果可能)是将其设置为[SerializeField]

[SerializeField] private Outline myScript;

并通过检查器直接引用它,而根本不必使用GetComponent。在字段中拖放相应的GameObject会自动获取相应的组件引用。


要启用或禁用它,只需设置MonoBehaviour.enabled

myScript.enabled = true; // or false

答案 1 :(得分:0)

如果它在您的父对象上,则:

myScript = gameObject.transform.parent.gameObject.GetComponent<Outline>();

雨果(Hugo)提出的其他好的解决方案(此处的性能并不是很关键)

myScript = gameObject.GetComponentInParent<Outline()>;

不是在统一环境中,但我认为在第二种情况下,gameObject是多余的。