在Unity中我们通常会遇到这样的场景,在一个不继承Monobehaviour类的类中,想使用Mono behaviour类中的方法,这时候我们应该怎么办呢?
这时候就需要我们在游戏中创建一个Mono管理器了,它的作用就是让我们可以在不继承Mono behaviour的类中使用Monobehaviour中的方法,那Mono管理器应该怎样写呢?接下来让我们来看一下。
首先我们先实现使用Mono管理器,开启协程,关闭协程的方法。
我们先创建一个Monocontroll类继承Monobehaviour
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MonoControll : MonoBehaviour
{
}
然后我们创建一个MonoManger类用来管理,当然MonoManger类需要继承单例模式基类,因为整个游戏中我们只需要一个MonoManger类即可。在MonoManger类中我们调用Monocontroll类中开启协程的方法,关闭协程的方法即可。当然我们还需要判断Monocontroll是否存在,如果不存在,我们需要使用代码创建一个游戏对象,并把Monocontroll脚本挂载上去。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
Title:
Description:
*/
public class MonoManger : Singleton<MonoManger>
{
private MonoManger() { }
private MonoControll monocontroll;
public MonoControll MonoControll
{
get
{
if(monocontroll==null)
{
GameObject go = new GameObject(typeof(MonoControll).Name);
monocontroll=go.AddComponent<MonoControll>();
}
return monocontroll;
}
}
public Coroutine Startcoroutine(IEnumerator routine)
{
return MonoControll.StartCoroutine(routine);
}
public void Stopcoroutine(Coroutine routine)
{
MonoControll.StopCoroutine(routine);
}
public void StopAllCoroutine()
{
MonoControll.StopAllCoroutines();
}
}
这样我们的MonoManger类中的协程部分就写完了。接下来我们可以实验一下是否成功
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
Title:
Description:
*/
public class Player
{
Coroutine coroutine;
public void Show()
{
coroutine= MonoManger.Instance.Startcoroutine(Mycoroutine());
}
public void Hide()
{
MonoManger.Instance.Stopcoroutine(coroutine);
}
public void HideAll()
{
MonoManger.Instance.StopAllCoroutine();
}
IEnumerator Mycoroutine()
{
while(true)
{
Debug.Log("11111111");
yield return null;
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test :MonoBehaviour
{
Player Player;
private void Awake()
{
Player = new Player();
}
private void OnGUI()
{
if(GUI.Button(new Rect(0,0,150f,50f),"开启协程"))
{
Player.Show();
}
if(GUI.Button(new Rect(0,100f,150f,50f),"关闭协程"))
{
Player.Hide();
}
if (GUI.Button(new Rect(0, 200f, 150f, 50f), "关闭所有协程"))
{
Player.HideAll();
}
}
}