find all objects with a particular name that have been scaled
I am quite new to c#
Some of my objects have been scaled up in Y to get some variation. I am wanting to find all of these models and put them in a list so I can easily select them and go right to them.
So assuming the name of the model has the word "Tree" in it. How can I go about selecting all of them that have had their scales adjusted?
I believe this is going to be a pretty simple script, but finding the correct syntax for this has been driving me up the wall.
Answer by Soos621 · Jun 01, 2016 at 04:08 PM
You want to attach the tree class to all the the trees in the scene. Then place the treemanager into an object anywhere. The tree will register itself with the manager class and the manager class will sort out the tree that are scaled and if you so choose how much they have been scaled
public class Tree (){
public bool hasBeenScaled;
public float scaleAmount;
private TreeManager tManager;
void Awake (){
/* there are much better ways of having the treemanager class reference found
but this will be fine */
tManager = GameObject.FindObjectWithType<TreeManager> ();
RegisterCurrentTree ();
}
void RegisterCurrentTree (){
tManager.RegisterTree(this);
}
}
public class TreeManager (){
// you need to use System.Collections.Generic to use lists and dictionaries
public List <Tree> allTrees = new List<Tree>();
public void RegisterTree (Tree _tree){
if(!allTrees.contains(_tree)){
allTrees.add(_tree);
}
}
public List<Tree> FindAllScaledTrees (){
List<Tree> scaledTrees = new List<Tree>();
foreach(Tree t in allTrees){
if(t.hasBeenScaled){
scaledTrees.add(t);
}
}
return scaledTrees;
}
public List<Tree> FindAllScaledTrees (float minScale, float maxScale){
List<Tree> chosenScaledTrees = new List<Tree>();
foreach(Tree t in allTrees){
if(t.hasBeenScaled){
if(t.scaleAmount >= minScale && t.scaleAmount <= maxScale){
chosenScaledTrees.add(t);
}
}
}
return chosenScaledTrees;
}
}
is there any way to do this without adding a tree class to each tree? no way to search for them by their name?
something along the lines of GameObject = GameObject.Find("tree")
yes but it is very impractical and slow. What you really want to do when you set up an environment in unity is to make a prefab of each object that you place in the scene, then use those prefabs to build the level that way when something like this comes along where say you need to add a script to every tree or rock you can just add the new script as a component to the prefab and all of the objects will update with that script
the only way i would know about finding all the trees in the scene would to tag them as "tree" and then gather every gameobject in the scene go through each one and check the tag then add it to the correct list, but you wont be able to figure out how much each tree has scaled either
Your answer