Unity: when I use raycast, getcomponet can not work under the if statement. I think the logic is reasonable. I do not know how to collect it...
I am a beginner about unity and C#. I need to make a planting game as my university project.
Right now, there are several objects, which are 1. a terrain model, 2. a hp bar, 3. some transparent cubes in one large empty object.
Cubes are above terrain model and play the role of grid. What I want is that when the player click those transparent cubes whose tags are "Land", trees are planted at the location of the cube and the clicked cube is destroyed. At the same time, the trees can be planted successfully only if the tag of that terrain model is "Plantable". Each successful planting action will decrease the hp of that land. Once the hp becomes 0, the tag of terrain model will become "Unplantable" and it can not be planted any more.
So, I mainly have two scripts. One is about raycast and the other one is about hp bar. However, my raycast script can not get the component of hp bar's script successfully.
My raycast script is
void Update()
{
if (!EventSystem.current.IsPointerOverGameObject())
{
if (Input.GetMouseButtonUp(0))
{
RaycastHit hit;
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
if (hit.collider.gameObject.tag == "Land")
{
if (GetComponent<HpBar2>().Farmland.tag == "Plantable")
{
objectHit = hit.transform;
Instantiate(Tree1, objectHit.transform.position + new Vector3(0, 0.5f, 0), Quaternion.identity);
Destroy(hit.transform.gameObject);
GetComponentInChildren<HpBar2>().DecreaseHP();
}
if (GetComponent<HpBar2>().Farmland.tag == "unPlantable")
{
Warning.SetActive(true);
}
}
and my hp bar's script is
void Start()
{
currentHP = maxHP;
}
void Update()
{
HealthSilder.value = currentHP / maxHP;
if (currentHP <= 30f)
{
Farmland.tag = "unPlantable";
}
if (currentHP > maxHP)
{
currentHP = maxHP;
}
}
public void DecreaseHP()
{
currentHP -= 30f;
}
I do not know what is the wrong about these scripts and they almost kill me...
Your answer
Follow this Question
Related Questions
Avoid using GetComponent to check if RayCast hit is interactable 0 Answers
2 same Scripts w/ GetComponent : one works, one doesn't 2 Answers
Is there a better way to check if a player is looking at a certain object? 0 Answers
Get component from parent of children hittet with raycast 1 Answer
How to change the enum value of an instance of a prefab being clicked 0 Answers