Unity3D不同脚本函数或参数之间调用
生活随笔
收集整理的這篇文章主要介紹了
Unity3D不同脚本函数或参数之间调用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
腳本通訊
假如,我們有兩個腳本:Main.cs,SliderControl.cs。現在希望從SliderControl.cs調用Main.cs內的函數或參數。
(一)、被調用腳本函數為static類型,調用時直接用 類名.參數
public class Main: MonoBehaviour {public static int index = 0; }// 在SliderControl.cs中調用index int para = Main.index;(二)、GameObject.Find(“腳本所掛載在的物體的名字”)找到游戲對象,再通過GetComponent<腳本名>().函數名()調用腳本中的函數,只能調用public類型函數
public class Main: MonoBehaviour {public Vector3 CalculateTransPose(){//注意:必須是public函數...} }// 在SliderControl.cs中調用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;//調用Main.cs中的CalculateTransPose函數Vector3 func= _GG1.GetComponent<Main>().CalculateTransPose();} }(三)、GameObject.Find(“腳本所在的物體的名字”).SendMessage(“函數名”);(還未嘗試)
//能調用public和private類型函數
據說,這是早期unity提供的方式,這個方法已經過時,在效率上比較低,故這里不再推薦。
參考鏈接
using System.Collections; using System.Collections.Generic; using UnityEngine;public class Enemy : MonoBehaviour {private void TakeDamage(){} }// 在其他腳本中調用TakeDamage()函數 GameObject.Find("Enemy_1").SendMessage("TakeDamage", SendMessageOptions.DontRequireReceiver); 除了SendMessage,還有SendMessageUpwards和BroadcastMessage函數,三個函數的參數相似,都是方法名+方法的參數+額外信息選項組成。SendMessageOptions
區別
SendMessage僅向指定對象的所有腳本推送消息
SendMessageUpwards向指定對象和它的所有父物體推送消息
BroadcastMessage向指定對象和它的所有子物體推送消息
注意:
傳遞的對象似乎一次只能傳一個變量,因此可以將多個變量打包進一個數組進行傳遞。
總結
以上是生活随笔為你收集整理的Unity3D不同脚本函数或参数之间调用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 前端学习(1557):安全问题
- 下一篇: 软件加注册机加卡密