- Home /
Simple In game search field
I have a few game objects that each have colliders. When I click the game object the console prints its name. Here is the script I have attached to each game object.
public void Start ()
{
string name = gameObject.name;
}
public void OnMouseDown()
{
Debug.Log(name);
}
I also have a input field and a button that I currently can type in the name of a game object and destroy it.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEditor;
public class Search : MonoBehaviour
{
public Cube cube;
public InputField Name;
public void start ()
{
GameObject selected = GameObject.Find (Name.text);
Destroy (selected);
}
}
Instead of Destroying the gameobject in the second script, how can I instead select the game objects collider as if I used OnMouseDown() from the first script; even more specifically How can I search the game object in the input field and "select" the gameobject as if I simple clicked on it by hand. This is what I am looking for:
public void start ()
{
GameObject selected = GameObject.Find (Name.text);
Activate (selected); //activate the mesh collider to trigger
//OnMouseDown from first script.
//I know this won't work, but I am not
// sure what the proper syntax is here.
}
Answer by Eudaimonium · Jun 24, 2016 at 09:25 AM
Make a script that you will attach to your selectable objects, and have a function in it for selecting it, for example:
//script is, say, Selectable.cs
public void Select()
{
//Do fancy stuff here - apply new graphics for selection, etc
}
Then, in your method where you fetch the input name:
public void Start()
{
GameObject selected = GameObject.Find (Name.text);
selected.GetComponent<Selectable>().Select();
}
The fancy part is fetching the component (script) of the targeted game object and calling it's predefined function.
Note: I noticed you called your method "start". If you wish it to execute at the start of the game, it needs to be called "Start".
Answer by ETech-Studios · Jun 24, 2016 at 04:11 PM
The name
string is a local variable. This means it can only be read / written by code in the method in which it was declared. You need to declare it oustide of any methods.
string name;
public void Start ()
{
name = gameObject.name;
}
public void OnMouseDown()
{
Debug.Log(name);
}
Also you can call OnMouseDown()
from another script.
public void start ()
{
GameObject selected = GameObject.Find (Name.text);
selected.OnMouseDown();
}