Access component from another script

前端 未结 2 539
渐次进展
渐次进展 2021-01-29 11:37

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

2条回答
  •  一向
    一向 (楼主)
    2021-01-29 12:26

    If they are on the same object than

    myScript = GetComponent();
    

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

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

    myScript = GetComponentInParent();
    

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

    [SerializeField] private Outline myScript;
    

    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.


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

    myScript.enabled = true; // or false
    

提交回复
热议问题