Access component from another script

前端 未结 2 540
渐次进展
渐次进展 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:12

    If its on your parent object then:

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

    Other good Solution(cos performance is not critical here) by Hugo:

    myScript = gameObject.GetComponentInParent<Outline()>;
    

    Not in unity enviroment but i think in the second case gameObject is redundant.

    0 讨论(0)
  • 2021-01-29 12:26

    If they are on the same object than

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

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

    myScript = GetComponentInParent<Outline>();
    

    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
    
    0 讨论(0)
提交回复
热议问题