您可以使用可编写脚本的对象来跟踪您的对象。对象只需在其OnEnable()和OnDisable()回调中将自身添加和删除到可脚本化对象的列表中即可。当一个对象删除自身时,您可以进行代码检查以查看是否不再有对象,并触发一个事件,您的场景中的某些事件会做出反应。
(可拖动对象)
public class DragableObject : MonoBehaviour{
//reference to the scriptable object
public DragableObjectSet RuntimeSet;
void OnEnable(){
RuntimeSet.Add(this);
}
void OnDisable(){
RuntimeSet.Remove(this);
//you can put code checking if the runtime set is empty here
//or you can put it in the DragableObjectSet Remove method
}
}
可编写脚本的对象示例代码
public DragableObjectSet : ScriptableObject
{
public List<DragableObject> RuntimeSet = new List<DragableObject>();
public void Add(DragableObject obj){
RuntimeSet.Add(obj);
}
public void Remove(DragableObject obj){
RuntimeSet.Remove(obj);
if(RuntimeSet.Count() == 0)
//some code here raising an event (if desired)
}
}
这种类型的对象称为运行时集,在本演讲中将围绕40分钟标记进行详细介绍。
https://www.youtube.com/watch?v=raQ3iHhE_Kk
,
您可以获得带有Object.FindObjectsOfType<ComponentType>();
且已启用某些组件的所有活动且尚未破坏的GameObject的数组。一旦有了,就可以查看该数组的长度。
因此,您可以在破坏/停用可拖动游戏对象的代码中执行以下操作:
GameObject otherObject = /* get draggable object to possibly destroy */;
if ( /* test to remove otherObject */ )
{
// deactivate the draggable object
otherObject.setActive = false;
// get all other draggable objects
DraggableObject[] remainingDraggableObjects = Object.FindObjectsOfType<DraggableObject>();
if (remainingDraggableObjects.Length == 0)
{
// there are no more active gameobjects with enabled DraggableObject component
// handle win condition here.
}
}
在您的特定示例中,它看起来可能像这样:
void OnCollisionEnter(Collision other)
{
if (other.gameObject.name == "cubo")
{
other.gameObject.setActive = false; // better than destroying in most cases
// get all other draggable objects
arrastrar[] remainingObjects = Object.FindObjectsOfType<arrastrar>();
if (remainingObjects.Length == 0)
{
// there are no more active gameobjects with enabled arrastrar component
// handle win condition here.
}
}
// ...
,
解决方案可能使用单例:
创建一个新的空GameObject并添加以下代码:
using UnityEngine;
public class TrashCounter : MonoBehaviour {
public static TrashCounter instance = null;
public int counter = 0;
void Awake(){ instance = this; }
}
现在,无论您在何处创建对象(或在任何对象代码的Start()
方法中),只需执行TrashCounter.instance.counter++
即可获得垃圾计数。
此后,每次执行TrashCounter.instance.counter--
并询问if(TrashCounter.instance.counter == 0) WinGame()
后,每次删除对象时都只需要更新此计数器即可。
本文链接:https://www.f2er.com/3163854.html