unity组件及脚本组件的引用

1.组件的调用

例如:AudioSource组件

AudioSource audio = this.GetComponent<AudioSource>();//获取组件

audio.play();//播放

 void Update()
    {
        if(Input.GetMouseButtonDown( 0 ))
        {
            PlayMusic();
        }

    }

    void PlayMusic()
    {
        // 获取组件
        AudioSource audio = this.GetComponent<AudioSource>();

        if( audio.isPlaying )
        {
            Debug.Log("* 停止播放");
            audio.Stop();
        }
        else
        {
            Debug.Log("* 开始播放音乐 ..");
            audio.Play();
        }
        
    }

2.调用其他节点的组件

定义一个相应的组件类型,拖入相关节点后,unity会自动引入

public AudioSource audio;

3.引用脚本组件

这是一个简单的引用其他节点脚本组件的例子,这是一个主控节点,总共引用了四个脚本组件。

//主控节点
public class MainControl : MonoBehaviour {
//引用脚本组件
	public Fan fan;
    public AudioSource audio;
    public Fly fly;
    public FlyTurn turn;

    // Use this for initialization
    void Start () {
       
    }
	
	// Update is called once per frame
	void Update () {
        if (Input.GetKeyDown(KeyCode.Space)) //按空格键触发事件
        {
            PlayMusic();//调用函数
        }
        DoWork();
    }

	void DoWork() {
		if(fan.rotateSpeed == 0)
        {
            fly.xSpeed = 0;//引用其他脚本组件的参数
            fly.zSpeed = 0;
        }
        else
        {
            fly.zSpeed = 0;
            fly.xSpeed = 0;
            turn.turnSpeed = 0;
            if (Input.GetKey(KeyCode.W)) fly.zSpeed = 50;
            if (Input.GetKey(KeyCode.S)) fly.zSpeed = -50;
            if (Input.GetKey(KeyCode.D)) fly.xSpeed = 50;
            if (Input.GetKey(KeyCode.A)) fly.xSpeed = -50;
            if (Input.GetKey(KeyCode.Q)) turn.turnSpeed = 30;
            if (Input.GetKey(KeyCode.E)) turn.turnSpeed = -30;
        }
	}

    void PlayMusic()
    {
        if (audio.isPlaying)
        {
            audio.Stop();
            fan.rotateSpeed = 0;
        }
        else
        {
            audio.Play();
            fan.rotateSpeed = 1000;
        }
    }

4.消息调用

这是另外一种实现调用其他脚本组件的方法,具体步骤:

(1)主控节点使用全局变量先声明一个节点变量:

public GameObject fanNode;

(2)在updata()函数下向该节点发送“消息”:

fanNode.SendMessage("对应节点下的某个函数名");

这个方法其实运用了“反射机制”,要求函数名必须与对应的节点下的函数名一致,才会调用相应的函数。

  • 16
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值