- Home /
how to cast found object by tagfind onto object
i define and gameobject, and want to use class FindObjectsWithTag to find exit objects "Player", then let defined object is found one. code is:
var go:GameObject; go = GameObject.FindGameObjectsWithTag("Player");
ERROR said: cannot convert UnityEngine.GameObject[] to UnityEngine.GameObject. so how can i do with this?
thank you.
Answer by Tom 10 · Nov 12, 2010 at 04:58 AM
FindGameObjectsWithTag will find ALL GameObjects with the specified tag, and those are all returned in an array (GameObject[]).
If you have just one GameObject tagged "Player", then do this instead:
go = GameObject.FindWithTag("Player");
If you have more than one GameObject tagged "Player", but you only want the first one found, then do this:
go = GameObject.FindGameObjectsWithTag("Player")[0];
But if you do that, and there are no GameObjects in your scene tagged "Player", then that will throw an exception. If GameObject.FindGameObjectsWithTag might not find any, then you can check for it like this:
var gos:GameObject[] = GameObject.FindGameObjectsWithTag("Player");
if(gos.length > 0) {
go = gos[0];
// use go for whatever you want
}
You can read more about GameObject.FindGameObjectsWithTag here.
Your answer
Follow this Question
Related Questions
Converting a GameObject to a class? 1 Answer
C# Casting Compile Error 1 Answer
Converting Variables 3 Answers
Converting file types 1 Answer