当前位置:   article > 正文

Unity代码基础之“组件的获取、禁用、调用其他脚本的方法”(2)_unity禁用组件代码

unity禁用组件代码
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class scene1 : MonoBehaviour
  5. {
  6. public scene1 exclusive_scene1;
  7. public GameObject play;
  8. public GameObject cameraMain;//将只能拖拽照相机组件
  9. public int hp = 100;
  10. // Start is called before the first frame update
  11. void Start()
  12. {
  13. //组件的获取、禁用、调用其他脚本的方法
  14. //1.拖拽赋值获取组件
  15. //1_1.代码:public scene1 Newscene1;
  16. //1_2.要满足2个条件才能拖拽
  17. //1_2_1.要是scene1这个脚本
  18. //1_2_2.scene1要挂在了组件上
  19. //2.访问自身的组件 - GetComponent
  20. Transform t = GetComponent<Transform>();
  21. //Debug.Log(t);
  22. //2_1.因为Transform组件是个内置组件所以我们可以直接用开头小写的transform(当前组件)就可以访问到了
  23. //2_2.因为一个游戏物体身上是可以挂载多个相同的组件的所以,就有一个GetComponents
  24. Collider[] colliders = GetComponents<Collider>();
  25. foreach(Collider a in colliders) {
  26. //Debug.Log(a);
  27. };
  28. //2_3.如果你只想得到一个碰撞器(在组件上点击Add Component添加的末尾带collider的)的话
  29. //Debug.Log(GetComponent<BoxCollider>());
  30. //2_4.GetComponent不管是被借用了,它都是可以接着使用的
  31. //Debug.Log(GetComponent<scene1>());
  32. //2_5.获取子物体身上的组件就可以(GetComponentinChilidren)
  33. //待补充
  34. //2_6.获取另外一个物体身上的组件
  35. //Debug.Log(play.GetComponent<Rigidbody>());
  36. //3.禁用组件、改变组件属性
  37. //3_1.先要获取这个组件,比如要禁用这个钢体组件
  38. BoxCollider boxc = play.GetComponent<BoxCollider>();
  39. boxc.enabled = false; //禁用
  40. //3_2.将BoxCollider组件的勾去掉,即使组件被禁用了,这个里面的方法还是可以调用的
  41. boxc.enabled = false; //禁用
  42. //3_3.调用其他脚本的几种方法scene1 与 scene2_a
  43. //在后面
  44. //3_4.改变组件的属性
  45. Rigidbody rdy = play.GetComponent<Rigidbody>();
  46. rdy.mass = 300;
  47. //4.获取游戏物体的四种方式
  48. //4_1.直接拖拽(访问相机)public GameObject cameraMain;
  49. //4_2.通过Find查找,只能查找子物体,性能高
  50. //Debug.Log(transform.Find("GameObject1/GameObject11"));
  51. //4_3.(不推荐使用,耗性能,是全局查找)利用 GameObject.Find("游戏物体名");
  52. //Debug.Log(GameObject.Find("Main Camera"));
  53. //4_4.(推荐)通过标签查找untagged(未指定标签),点击Ad tag添加标签,也可以使用内置标签
  54. GameObject tag = GameObject.FindWithTag("play");
  55. //Debug.Log(tag);
  56. }
  57. // Update is called once per frame
  58. void Update()
  59. {
  60. }
  61. }

调用其他的脚本

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class scene2 : MonoBehaviour
  5. {
  6. // Start is called before the first frame update
  7. //5.调用其他脚本的几种方法
  8. //5_1.用new定义
  9. //scene1 t = new scene1();
  10. //暂不做探讨
  11. //5_2.用public定义类型
  12. public scene1 t;
  13. //5_3.可以用static添加静态.这样就可以直接scene1.Start();
  14. //暂不做探讨
  15. void Start()
  16. {
  17. t.enabled = false;//就算禁用了脚本,它的方法还是会执行的
  18. Debug.Log(t.hp);//打印要写方法里面,获取不要写在方法里面,不然不生效
  19. }
  20. // Update is called once per frame
  21. void Update()
  22. {
  23. }
  24. }

 

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

闽ICP备14008679号