- Home /
Need an advise, how to find all objects with a specific name and a specific script?
So i have two scripts. Script Leaders is attached to some objests on the scene,script Follower is to move an object to objects with attached script Leaders.If i have one object everything works fine,im clicking at object for examole a cube, than im clicking at a spot,its moving to this spot. But if im having two or more objects,only one is moving or doing something.This happening i guess because its finding only one object follower = GameObject.Find("Follower").GetComponent< Follower>(); So my question is, how to make this line like to be something like an array to store information of all objects on the scene? Thanks for ant help.
public class Leaders : MonoBehaviour
{
private Follower follower;
void Start ()
{
follower = GameObject.Find("Follower").GetComponent< Follower>();
}
void OnMouseDown()
{
if(follower.selected == true)
{
follower.v3Dest = transform.position;
follower.selected = false;
}
}
public class Follower : MonoBehaviour
{
public Vector3 v3Dest;
public bool selected = false;
public float speed = 5.0f;
void Start ()
{
v3Dest = transform.position;
}
void Update ()
{
transform.position = Vector3.MoveTowards(transform.position,v3Dest,Time.deltaTime * speed);
transform.LookAt(v3Dest);
}
void OnMouseDown()
{
selected = true;
}
}
look at GameObject.FindGameObjectsWithTag
you will need to use tags ins$$anonymous$$d, but it should give you all the objects you want
Answer by Bunny83 · May 10, 2013 at 11:24 PM
It's way easier to directly search for your Follower scripts. Just use FindObjectsOfType:
public class Leaders : MonoBehaviour
{
private Follower[] followers;
void Start ()
{
followers = FindObjectsOfType(typeof(Follower)) as Follower[];
}
void OnMouseDown()
{
foreach(var follower in followers)
{
if(follower.selected == true)
{
follower.v3Dest = transform.position;
follower.selected = false;
}
}
}
}
ps you might want to rename your "Leaders" class to "Leader" because one instance is just a leader ;)
But i guess for is faster,so im using:
for(int i = 0;i<followers.Length;i++)
{
if(followers[i].selected == true)
{
followers[i].v3Dest = transform.position;
followers[i].selected = false;
}
}
But Thank you :D
Answer by weltraumaffe · May 10, 2013 at 11:05 PM
GameObject.Find()
finds only one GameObject. With GameObject.FindGameObjectsWithTag()
you can find every Game Object with a specific tag.
Beware: Find functions are very slow and shouldn't be used too often (or even repetitively in Update()...)
Your answer
Follow this Question
Related Questions
Get variable in script got by get component c# 2 Answers
GetComponent of Game Objects in an array 1 Answer
Distribute terrain in zones 3 Answers
Retrieve an integer from an array in a different script 1 Answer
Using getcomponent with an array 2 Answers