当前位置:   article > 正文

Unity3D 引用其他脚本组件_unity怎么引用其他脚本

unity怎么引用其他脚本

本文介绍在一个脚本里,如何访问另一个脚本组件。

和普通组件一样,也有2种方法

1 API 获取  

 FanLogic fan = node.getComponent<FanLogic>();

实例:

1.1在风扇下面添加FanLogic脚本

1.2FanLogic脚本代码如下

1.3 在游戏主控下面添加MainLogic脚本

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class MainLogic : MonoBehaviour
  5. {
  6. // 目标组件,直接在检查里引用
  7. public GameObject fanNode;
  8. // Start is called before the first frame update
  9. void Start()
  10. {
  11. }
  12. // Update is called once per frame
  13. void Update()
  14. {
  15. if(Input.GetMouseButtonDown(0))
  16. {
  17. DoWork();
  18. }
  19. }
  20. void DoWork()
  21. {
  22. FanLogic fan = fanNode.GetComponent<FanLogic>();
  23. }
  24. }

 

2 直接引用    

public FanLogic fan;

只需修改MainLogic脚本如下

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class MainLogic : MonoBehaviour
  5. {
  6. // 目标组件,直接在检查里引用
  7. public FanLogic fan;
  8. // Start is called before the first frame update
  9. void Start()
  10. {
  11. }
  12. // Update is called once per frame
  13. void Update()
  14. {
  15. if(Input.GetMouseButtonDown(0))
  16. {
  17. DoWork();
  18. }
  19. }
  20. void DoWork()
  21. {
  22. //FanLogic fan = fanNode.GetComponent<FanLogic>();
  23. fan.rotateSpeed = 180;
  24. }
  25. }

其他操作不变

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/木道寻08/article/detail/998620
推荐阅读
相关标签
  

闽ICP备14008679号