Unity中随机出现和消失的对象 [英] Randomly appearing and disappearing objects in Unity
问题描述
我想使用SetActive(True/False)
命令在Unity3d中创建一个随机出现和消失的对象.我不希望它移动到任何地方,并且我正在使用Unity3d C#(对于需要了解的人),我还没有尝试过任何东西.
I would like to make an object in Unity3d that reappears and disappears randomly using theSetActive(True/False)
command. I don't want it to move anywhere and I'm using Unity3d C# (for those who need to know) I haven't tried anything yet.
推荐答案
如果您不希望使用使用字符串查找方法名称的安全,快速的方法(通常是个坏主意),则可以使用协程:
If your prefer a safer and faster approach w/out using strings to look up method names (which is usually a bad idea), you can use a coroutine:
using UnityEngine;
using System.Collections;
public class ToggleVisibility : MonoBehaviour
{
public GameObject GameObjectToHide;
public float MinTime = 2.0f;
public float MaxTime = 5.0f;
void Start()
{
StartCoroutine(ToggleVisibilityCo(GameObjectToHide));
}
IEnumerator ToggleVisibilityCo(GameObject someObj)
{
if (someObj == null) yield break;
while(true)
{
someObj.SetActive(!someObj.active);
yield return new WaitForSeconds(Random.Range(MinTime, MaxTime));
}
}
}
但是,您必须考虑到-无论您采用哪种方法-如果将对象设置为非活动状态,它包含的所有MonoBehaviours都将停止工作,因此您需要将此脚本放入处于活动状态的GameObject中,并在检查器GameObjectToHide
,它将被实际激活/禁用.参见有关如何在检查器中连接元素的图像
However you must take into account that -whatever approach you follow- if you set an object inactive, all MonoBehaviours that it contains will stop working, so you need to put this script in a GameObject that is active, and set in the inspector the GameObjectToHide
which will be the one that will be actually activated/deactivated. See the image on how to wire the elements in the inspector
这篇关于Unity中随机出现和消失的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!