I wanted to obtain the index of a gameobject when clicked and interact with the selected gameobject. I Instantiate a prefab using another script “myGUI” using the GUI button… When the GUI button is pressed and I click on the terrain… the prefab is then instantiated on the position of the input.mousePosition on the terrain. How do I find the index of a gameobject and interact with it individually when multiple prefabs of the same game object are instantiated.
Here’s a sample Code in an attempt to find the index:
public class IndexSelect : MonoBehaviour {
//Array list for identifying indexes
static ArrayList MovePlayer = new ArrayList();
int i;
//End Array list
RaycastHit hit;
public Light myLight;
public bool Selected = false;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Ray ray = camera.ScreenPointToRay(Input.mousePosition);
//Debug.DrawRay(ray.origin, ray.direction * 100, Color.green);
if(Physics.Raycast(ray, out hit, 100))
{
print ("Here is an object!");
if (hit.transform.gameObject.tag == ("Ground")){
//Debug.DrawRay(ray.origin, ray.direction * 100, Color.red);
print ("Ray has Hit the Ground");
}
else if (hit.transform.gameObject.tag == ("Player")){
Debug.DrawRay(ray.origin, ray.direction * 100, Color.blue);
if ((Input.GetMouseButtonDown(0))&&(hit.transform.gameObject.tag == "Player")){
print("You Clicked the Player!");
GameObject[] light = GameObject.FindGameObjectsWithTag("Player");
myLight = light*.GetComponent<Light>();*
-
myLight.enabled = true;* -
Selected = true; * -
}* -
else* -
{* -
}* - }*
}
You can think another way, example you can attach a simple script like that to the object tag "Player" public class PlayerClick: MonoBehaviour { void OnMouseDown() { //this function is called whenever the mouse is over the object gameObject.light.enable = true; } } And there are many ways to get the Selected variable set to true.
– nixcs2512