Is there something like a “Find Game Object That Has a Certain Value in a Variable” to find a specific object?
I am UBER noob at Unity and coding, I only do this as a hobby. So please be very specific if you answer :). I am trying to make a little game where the player navigates through tiles and gains resources and spends them to move, etc.
Here is what it looks like in Game View: http://imgur.com/RhxdImS
This is the script attached to all my tiles that
- Turns the original selected tile to red.
- When you click on a tile to select it, it turns the one that was previously selected to white and
- It turns the one you just clicked on to red.
In C#:
using UnityEngine;
using System.Collections;
public class TileScript : MonoBehaviour
{
void Start()
{
// put color of the first tile to red
if (gameObject.tag == "Selected Tile")
{
GetComponent<Renderer>().material.color = Color.red;
}
}
GameObject SelectedTile;
void OnMouseDown()
{
// change tag from Selected Tile to Tile
SelectedTile = GameObject.FindGameObjectWithTag("Selected Tile");
SelectedTile.gameObject.tag = "Tile";
SelectedTile.gameObject.GetComponent<Renderer>().material.color = Color.white;
// change tag to Selected Tile
gameObject.tag = "Selected Tile";
// change color according to tag
if (gameObject.tag == "Selected Tile")
{
GetComponent<Renderer>().material.color = Color.red;
}
}
}
I understand that Unity objects have tags, which help to identify them in codes. Right now, I have two tags: “Tile” and “Selected Tile”. This is what my script uses to identify which game object is the “Selected Tile”.
The problem is that I would like to use these tags to determine whether a tile is, for example, a “Forest Tile” or a “Mountain Tile” or a “Valley Tile” in order to code the effect that each tile has on the player when the player arrives on a tile. i.e. [the selection].
To do this, I need to make the selection process use a different method than by tag, so I imagine that creating a boolean variable “Selected” in each object would be a good way? Now I do know how to find an object by its tag or its name, but I do not know how to find an object by the value of a variable that is in a script component of a game object.