从另一个脚本访问组件 [英] Access component from another script

查看:62
本文介绍了从另一个脚本访问组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Im using unity and I have Im trying to access a script called Outline on my parent object. I need to disable and enable the script Outline from another script called Destroyable. I know theres a ton of tutorials out there and other questions asked but it always seems to not be able to find it.

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()
    {

    }
}

推荐答案

如果它们在同一对象上

myScript = GetComponent<Outline>();

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

should already give you the reference you want.

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

Otherwise if you say it is on the parent object than you should instead use

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

GetComponentInParent (仅在启用了组件且激活了GameObject的情况下)在开始时)

or GetComponentInParent (only if the component is enabled and the GameObject active on Start)

myScript = GetComponentInParent<Outline>();


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


Even better (if possible) would be you make it a [SerializeField]

[SerializeField] private Outline myScript;

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

and directly reference it via the Inspector than you don't have to use GetComponent at all. Drag&Drop the according GameObject in the field it automatically gets the according component reference.

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

In order to then enable or disable it simply set MonoBehaviour.enabled

myScript.enabled = true; // or false

这篇关于从另一个脚本访问组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆