get gameobject by name unity code example
Example 1: how to find gameobjects in unity
using UnityEngine;
using System.Collections;
// This returns the GameObject named Hand in one of the Scenes.
public class ExampleClass : MonoBehaviour
{
public GameObject hand;
void Example()
{
// This returns the GameObject named Hand.
hand = GameObject.Find("Hand");
// This returns the GameObject named Hand.
// Hand must not have a parent in the Hierarchy view.
hand = GameObject.Find("/Hand");
// This returns the GameObject named Hand,
// which is a child of Arm > Monster.
// Monster must not have a parent in the Hierarchy view.
hand = GameObject.Find("/Monster/Arm/Hand");
// This returns the GameObject named Hand,
// which is a child of Arm > Monster.
hand = GameObject.Find("Monster/Arm/Hand");
}
}
Example 2: how to access gameobject name
// note how the 'g' is lowercase, when it's lowercase it accesses the GameObject its attached to
gameObject.name
// so if this script was attached an object named "Player", it will access "Player"
Example 3: get gameobject by name
using UnityEngine;
using System.Collections;// This returns the GameObject named Hand in one of the Scenes.public class ExampleClass : MonoBehaviour
{
public GameObject hand; void Example()
{
// This returns the GameObject named Hand.
hand = GameObject.Find("Hand"); // This returns the GameObject named Hand.
// Hand must not have a parent in the Hierarchy view.
hand = GameObject.Find("/Hand"); // This returns the GameObject named Hand,
// which is a child of Arm > Monster.
// Monster must not have a parent in the Hierarchy view.
hand = GameObject.Find("/Monster/Arm/Hand"); // This returns the GameObject named Hand,
// which is a child of Arm > Monster.
hand = GameObject.Find("Monster/Arm/Hand");
}
}
Example 4: unity find game object by name
//tag
foreach(GameObject fooObj in GameObject.FindGameObjectsWithTag("foo"))
{
if(fooObj.name == "bar")
{
//Do Something
}
}
//isim
foreach (var obje in FindObjectsOfType(typeof(GameObject)) as GameObject[])
{
if(obje.name == "obje")
{
//Do something...
}
}
Example 5: unity get object by name
function Update() { var enemy : GameObject = GameObject.Find("enemy"); //perform operations on enemy here}
Example 6: what does gameobject.find return
//It returns null/void