一定要在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 对象的类就不要继承默认的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(); }