首页 > 解决方案 > 从另一个脚本访问组件

问题描述

我正在使用统一,我试图访问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()
    {

    }
}

标签: unity3d

解决方案


如果它们在同一个物体上

myScript = GetComponent<Outline>();

应该已经给你你想要的参考。

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

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

GetComponentInParent(仅当组件已启用且游戏对象在开始时处于活动状态)

myScript = GetComponentInParent<Outline>();

更好的(如果可能的话)是你把它变成一个[SerializeField]

[SerializeField] private Outline myScript;

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


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

myScript.enabled = true; // or false

推荐阅读