Unity3D不同脚本函数或参数之间调用

脚本通讯

假如,我们有两个脚本:Main.csSliderControl.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 update
    void Start()
    {
    
    
        silder = GetComponent<Slider>();
    }

    // Update is called once per frame
    void 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

  1. SendMessageOptions.RequireReceiver //如果没有找到相应函数,会报错(默认是这个状态)
  2. SendMessageOptions.DontRequireReceiver //即使没有找到相应函数,也不会报错,自动忽略

区别
SendMessage仅向指定对象的所有脚本推送消息
SendMessageUpwards向指定对象和它的所有父物体推送消息
BroadcastMessage向指定对象和它的所有子物体推送消息

注意:
传递的对象似乎一次只能传一个变量,因此可以将多个变量打包进一个数组进行传递。

猜你喜欢

转载自blog.csdn.net/qq_41598072/article/details/125806047
今日推荐