Unity3D不同脚本函数或参数之间调用
腳本通訊
假如,我們有兩個(gè)腳本:Main.cs,SliderControl.cs。現(xiàn)在希望從SliderControl.cs調(diào)用Main.cs內(nèi)的函數(shù)或參數(shù)。
(一)、被調(diào)用腳本函數(shù)為static類型,調(diào)用時(shí)直接用 類名.參數(shù)
public class Main: MonoBehaviour {public static int index = 0; }// 在SliderControl.cs中調(diào)用index int para = Main.index;(二)、GameObject.Find(“腳本所掛載在的物體的名字”)找到游戲?qū)ο?#xff0c;再通過GetComponent<腳本名>().函數(shù)名()調(diào)用腳本中的函數(shù),只能調(diào)用public類型函數(shù)
public class Main: MonoBehaviour {public Vector3 CalculateTransPose(){//注意:必須是public函數(shù)...} }// 在SliderControl.cs中調(diào)用CalculateTransPose() public class SliderControl : MonoBehaviour {private Slider silder;public GameObject _GG1;// Start is called before the first frame updatevoid Start(){silder = GetComponent<Slider>();}// Update is called once per framevoid Update(){silder.value += 0.1f * Time.deltaTime;//調(diào)用Main.cs中的CalculateTransPose函數(shù)Vector3 func= _GG1.GetComponent<Main>().CalculateTransPose();} }(三)、GameObject.Find(“腳本所在的物體的名字”).SendMessage(“函數(shù)名”);(還未嘗試)
//能調(diào)用public和private類型函數(shù)
據(jù)說,這是早期unity提供的方式,這個(gè)方法已經(jīng)過時(shí),在效率上比較低,故這里不再推薦。
參考鏈接
using System.Collections; using System.Collections.Generic; using UnityEngine;public class Enemy : MonoBehaviour {private void TakeDamage(){} }// 在其他腳本中調(diào)用TakeDamage()函數(shù) GameObject.Find("Enemy_1").SendMessage("TakeDamage", SendMessageOptions.DontRequireReceiver); 除了SendMessage,還有SendMessageUpwards和BroadcastMessage函數(shù),三個(gè)函數(shù)的參數(shù)相似,都是方法名+方法的參數(shù)+額外信息選項(xiàng)組成。SendMessageOptions
區(qū)別
SendMessage僅向指定對(duì)象的所有腳本推送消息
SendMessageUpwards向指定對(duì)象和它的所有父物體推送消息
BroadcastMessage向指定對(duì)象和它的所有子物體推送消息
注意:
傳遞的對(duì)象似乎一次只能傳一個(gè)變量,因此可以將多個(gè)變量打包進(jìn)一個(gè)數(shù)組進(jìn)行傳遞。
總結(jié)
以上是生活随笔為你收集整理的Unity3D不同脚本函数或参数之间调用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 前端学习(1557):安全问题
- 下一篇: 前端学习(1797):前端调试之html