[TUTORIAL] Busca Customizada De Objetos Na Cena
Página 1 de 1
[TUTORIAL] Busca Customizada De Objetos Na Cena
Criei esse Script quase semelhante as funcoes
ele faz exatamente o mesmo do citado acima, retorna um gameObject ou um array de gameObject , más ele é o tipo personalizado, eu criei 2 tipos de referencias "category" e "group", a diferença deles pro dá unity é que voçe só podem modificar a categoria ou grupo pegando o script e atribuindo valor
o script que envia a referencia Script iCategory.cs (coisa simples) basta add em qualquer gameobject que precise retornar mais tarde
Script das funçoes personalizadas Extra.cs , basta criar arquivo cs e colar salvar em qualquer lugar do projeto, nao precisa add a nenhum objeto
e por ultimo o script de teste
Teste.cs
claro, nao espero que seja muito usado, mas o objetivo aqui é demonstrar o poder do nosso cerebro , qualquer modifiçao tmb poderia ser implementada, por exemplo buscar gameobjects pelo mesmo ID, etc..
- Código:
GameObject.FindGameObjectsWithTag(string tag)
GameObject.Find(string name)
ele faz exatamente o mesmo do citado acima, retorna um gameObject ou um array de gameObject , más ele é o tipo personalizado, eu criei 2 tipos de referencias "category" e "group", a diferença deles pro dá unity é que voçe só podem modificar a categoria ou grupo pegando o script e atribuindo valor
o script que envia a referencia Script iCategory.cs (coisa simples) basta add em qualquer gameobject que precise retornar mais tarde
- Código:
using UnityEngine;
//como usar
//adicione esse script a qualquer objeto que voce queira dar referencia depois
//edite a categoria e grupo como preferir
//use as funçoes contidas no script Extra para localizar os gameobjects com estas referencias
//identico a buscar por tag, nome, etc, customizado
public class ICategory : MonoBehaviour
{
public string category="default";
public string group="default";
// Start is called before the first frame update
}
Script das funçoes personalizadas Extra.cs , basta criar arquivo cs e colar salvar em qualquer lugar do projeto, nao precisa add a nenhum objeto
- Código:
using System.Collections.Generic;
using UnityEngine;
//salve este script em qualquer lugar nao é preciso adicionar a nenhum objeto.
// somente as funcoes/metodos que serao
//usados atraves do seu script atual
public sealed class Extra : Object
{
/// <summary>
/// retorna um gameobject que esteja com a categoria marcada como categoryName
/// </summary>
/// <param name="categoryName">a categoria a buscar</param>
/// <returns></returns>
public static GameObject FindGameObjectByCategory(string categoryName)
{
var gameObj = GameObject.FindObjectsOfType<GameObject>();
GameObject target = null;
for (int x = 0; x < gameObj.Length; x++)
{
var selector = gameObj[x];
var hasComponent = selector.GetComponent<ICategory>() != null ? true : false;
if (hasComponent && gameObj[x].GetComponent<ICategory>().category == categoryName)
{
target = gameObj[0];
}
}
if (target != null)
return target;
else
throw new System.Exception("Can´t Find or Not Found gameobject with category: "" + categoryName + """);
}
/// <summary>
/// retorna um gameobject que esteja com o grupo marcado groupName
/// </summary>
/// <param name="groupName">grupo a ser buscado</param>
/// <returns></returns>
public static GameObject FindGameObjectByGroup(string groupName)
{
var gameObj = GameObject.FindObjectsOfType<GameObject>();
GameObject target = null;
for (int x = 0; x < gameObj.Length; x++)
{
var selector = gameObj[x];
var hasComponent = selector.GetComponent<ICategory>() != null ? true : false;
if (hasComponent && gameObj[x].GetComponent<ICategory>().category == groupName)
{
target = gameObj[0];
}
}
if (target != null)
return target;
else
throw new System.Exception("Can´t Find or Not Found gameobject with group: "" + groupName + """);
}
/// <summary>
/// retorna um array de gameobjects marcados como o mesmo nome da categoryName (identico a GameObject.FindGameObjectsWithTag())
/// </summary>
/// <param name="categoryName">categoria a ser buscada</param>
/// <returns></returns>
public static GameObject[] FindGameObjectsByCategory(string categoryName)
{
var gameObj = GameObject.FindObjectsOfType<GameObject>();
var res = new List<GameObject>();
for (int x = 0; x < gameObj.Length; x++)
{
var selector = gameObj[x];
var hasComponent = selector.GetComponent<ICategory>() != null ? true : false;
if (hasComponent && gameObj[x].GetComponent<ICategory>().category == categoryName)
{
res.Add(gameObj[x]);
}
}
if (res != null && res.Count > 0)
return res.ToArray();
else
throw new System.Exception("Can´t Find or Not Found gameobjects with category: "" + categoryName + """);
}
/// <summary>
/// retorna um array de gameobjects marcados como o mesmo nome do groupName (identico a GameObject.FindGameObjectsWithTag())
/// </summary>
/// <param name="groupName">o grupo a ser buscado</param>
/// <returns></returns>
public static GameObject[] FindGameObjectsByGroup(string groupName)
{
var gameObj = GameObject.FindObjectsOfType<GameObject>();
var res = new List<GameObject>();
for (int x = 0; x < gameObj.Length; x++)
{
var selector = gameObj[x];
var hasComponent = selector.GetComponent<ICategory>() != null ? true : false;
if (hasComponent && gameObj[x].GetComponent<ICategory>().group == groupName)
{
res.Add(gameObj[x]);
}
}
if (res != null && res.Count > 0)
return res.ToArray();
else
throw new System.Exception("Can´t Find or Not Found gameobjects with group: "" + groupName + """);
//return null;
}
}
e por ultimo o script de teste
Teste.cs
- Código:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//adicionado em um objeto qualquer
public class Teste : MonoBehaviour
{
public GameObject[] categoryObj; //categorias
public GameObject[] groupObj; //grupos
GameObject obj1;
// Start is called before the first frame update
void Start()
{
obj1 = Extra.FindGameObjectByCategory("cubo");
obj1.name = "categoriacubo";
categoryObj = Extra.FindGameObjectsByCategory("cubo"); //retorna todos os gameobjects q tenha a categoria cubo
groupObj = Extra.FindGameObjectsByGroup("sphere"); //retorna todos os gameobjects q tenha o grupo sphere
foreach (GameObject obj in categoryObj)
{
print("este objeto tem a categoria cubo: " + obj.name);
}
foreach (GameObject obj2 in groupObj)
{
print("este objeto tem o groupName sphere: " + obj2.name);
}
}
}
claro, nao espero que seja muito usado, mas o objetivo aqui é demonstrar o poder do nosso cerebro , qualquer modifiçao tmb poderia ser implementada, por exemplo buscar gameobjects pelo mesmo ID, etc..
Tópicos semelhantes
» [TUTORIAL] GameObject.FindWithTag ( Achar objetos na cena pelas Tags )
» [TUTORIAL] Acessar diversos objetos em cena e ataca-los separadamente se estiver perto
» Destruir todos os objetos em cena.
» OBJETOS FICAM INVISÍVEIS NA CENA
» [Resolvido]Trocar cena ao eliminar objetos
» [TUTORIAL] Acessar diversos objetos em cena e ataca-los separadamente se estiver perto
» Destruir todos os objetos em cena.
» OBJETOS FICAM INVISÍVEIS NA CENA
» [Resolvido]Trocar cena ao eliminar objetos
Página 1 de 1
Permissões neste sub-fórum
Não podes responder a tópicos