【unity】基础交互入门(C#脚本互相调用的方法,含动态绑定脚本)

一、单例模式

脚本A:
在需要被调用的类里这样写:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class UIControl : MonoBehaviour
{
    
    
    public static UIControl UIController;//创建静态对象,此时对象为空
    private void Awake()
    {
    
    
        UIController = this;//一定要在Awake里面初始化对象
    }
    public void switchBag()//这个方法就可以被调用了,方法一定用public修饰才能被访问
    {
    
       
    }
}

脚本B:
在其他类里调用:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameControl : MonoBehaviour
{
    
    
    void myFunc(){
    
    
    	UIControl.UIController.switchBag();//这样就调用到了上个类的方法
    }
}

如果出现无法识别上下文的提示,检查一下以下问题:
1、两个脚本的命名空间是否一致,如果不需要的命名空间可以直接删除。
2、类名是否大写开头,且命名合法,且和文件名一致。
3、更新编译一下保存一下脚本,排除引用的脚本没保存编译的情况。

二、new 对象

脚本A:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlaceControl//工具类就不要继承MonoBehaviour了
{
    
    
    public void move(){
    
    
    }
}

脚本B:
实例化:new PlaceControl ()

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameManager : MonoBehaviour
{
    
    
	private PlaceControl placement;
	private Start(){
    
    
		placement = new PlaceControl ();
		placement.move();
	}
}

三、动态绑定脚本

脚本A:
需要被调用的类:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class UIControl : MonoBehaviour
{
    
    
    // Start is called before the first frame update
    void Start()
    {
    
    
    }
    // Update is called once per frame
    void Update()
    {
    
    
    }
    void switchBag()
    {
    
    
    }
}

脚本B:
动态绑定并调用:


void getCard()
{
    
    
  //找到对象列表
   GameObject cardList = GameObject.Find("cardList");
   CreateCard(cardList);
}

void CreateCard(GameObject cardList)
 {
    
    
   //创建对象
   GameObject CardObj = new GameObject("card");
   //添加到对象列表
   CardObj .transform.SetParent(itemList.transform, false);
   //给对象绑定可视范围脚本
   CardObj .AddComponent<UIControl>();
   //触发方法
   CardObj .GetComponent<UIControl>().switchBag();    
 }

猜你喜欢

转载自blog.csdn.net/qq_35079107/article/details/129028315