using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
public class TestCooroutine : MonoBehaviour
{
public string goName;
public TestCooroutine testCooroutine;
public Coroutine thisCoroutine;
private void Start()
{
goName = gameObject.name;
thisCoroutine = StartCoroutine(Coroutinee());
testCooroutine = GetComponent<TestCooroutine>();
}
private void Update()
{
// Debug.Log("一直在运行奥");
if (Input.GetKeyDown(KeyCode.Q))
{
testCooroutine.enabled = false;
}
else if (Input.GetKeyDown(KeyCode.W))
{
gameObject.SetActive(false); // 禁用整个 GameObject
}
else if (Input.GetKeyDown(KeyCode.E))
{
Destroy(gameObject); // 销毁 GameObject
}
else if (Input.GetKeyDown(KeyCode.R))
{
StopCoroutine(Coroutinee());
}
else if(Input.GetKeyDown(KeyCode.T))
{
SceneManager.LoadScene("Test2");
}
else if (Input.GetKeyDown(KeyCode.Y))
{
enabled = false;
}
else if (Input.GetKeyDown(KeyCode.U))
{
StopAllCoroutines();
}
else if (Input.GetKeyDown(KeyCode.I))
{
StopCoroutine(thisCoroutine);
}
}
IEnumerator Coroutinee()
{
int circle = 15;
while (circle > 0)
{
Debug.Log(goName + ":" + circle--);
yield return new WaitForSeconds(1);
}
Debug.Log(goName+"已结束正常并退出");
}
}
cs复制代码
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class Test2 : MonoBehaviour
{
private List<GameObject> _go;
private void Start()
{
var test = FindObjectsOfType<TestCooroutine>().ToList();
_go = test.Select(x => x.gameObject).ToList();
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.O))
{
for (int i = 0; i < _go.Count; i++)
{
_go[i].SetActive(true);
}
Debug.Log("恢复了");
}
}
}