Unity中使用C#脚本时不同类之间相互调用方法

第一种:使用单例模式

一定要在awake里面赋值对象

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

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

这样就可以在其他类里面使用Player里面的方法了

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

public class GameManager : MonoBehaviour
{
    void Fire(){
    	Player.player.LisaerFire();//这样就调用到了上个类的方法
    }
}

同样的,在GamaManager里面也可以是使用单例模式,让Player调用其方法

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

public class GameManager : MonoBehaviour
{
	public static GameManager gm;
    private void Awake()
    {
        gm= this;
    }
    public void Attack()//这个方法就可以被调用了
    {   
    }
}

第二种 new 对象

如下
new 对象的类就不要继承默认的MonoBehaviour

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

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

此时在其他类可以new Inputletter()了

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

public class GameManager : MonoBehaviour
{
	private Inputletter in;
	private Start(){
		in = new Inputletter ();
	}
}

第三种 获取游戏对象组件

GameObject.GetComponent().GameOver();//调用游戏对象上面的Cat脚本里面的GameOver方法

//在pos.position位置、catPrefab.transform.rotation角度生成一个catPrefab游戏对象
GameObject.Instantiate(catPrefab ,pos.position , catPrefab.transform.rotation)

     	  private Cat cat1;//以类名(脚本名)为类型创建一个叫cat1的变量
          void XX()//写在方法里面
          {
              cat1 = GameObject.Instantiate(catPrefab ,pos.position , catPrefab.transform.rotation).GetComponent<Cat>();
                     //实例化游戏对象后得到预制体的脚本组件
          }
          void SS()//就可以调用了
          {
              cat1.Miao();
          }
  • 8
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值