引用别的组件

当 GameObject 要访问其它对象上的组件时,有下面两种方法

方法一(推荐)

public class MainLogic : MonoBehaviour
{
    public AudioSource bgm;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            if (bgm.isPlaying)
            {
                bgm.Pause();
            }
            else
            {
                bgm.Play();
            }
        }
    }
}

方法二

public class MainLogic : MonoBehaviour
{
    public GameObject bgmNode;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            if (bgmNode.GetComponent<AudioSource>().isPlaying)
            {
                bgmNode.GetComponent<AudioSource>().Pause();
            }
            else
            {
                bgmNode.GetComponent<AudioSource>().Play();
            }
        }
    }
}

posted @ 2024-07-15 20:34  暖暖De幸福  阅读(2)  评论(0编辑  收藏  举报