how do i Find an Object in the same hierarchy?
How do i Find the HealthBar i can't use bar = transform.find().getcomponent< BarScript >();
Player
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class Player : MonoBehaviour {
[SerializeField]
private Stat health;
private void Awake()
{
//health.initialize();
}
private void Start()
{
health.initialize();
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.Q))
{
health.CurrentVal -= 10;
}
if (Input.GetKeyDown(KeyCode.W))
{
health.CurrentVal += 10;
}
if (Input.GetKeyDown(KeyCode.Z))
{
health.MaxVal -= 10;
}
if (Input.GetKeyDown(KeyCode.X))
{
health.MaxVal += 10;
}
}
}
Stat
using UnityEngine;
using System.Collections;
using System;
[Serializable]
public class Stat
{
[SerializeField]
private BarScript bar;
[SerializeField]
private float maxVal;
[SerializeField]
private float currentVal;
public float CurrentVal
{
get
{
return currentVal;
}
set
{
this.currentVal = Mathf.Clamp(value, 0, MaxVal);
bar.Value = currentVal;
}
}
public float MaxVal
{
get
{
return maxVal;
}
set
{
maxVal = value;
bar.MaxValue = maxVal;
}
}
public BarScript Bar
{
get
{
return bar;
}
set
{
bar = value;
}
}
Transform FindChild(string name, Transform t)
{
if (t.name == name)
return t;
foreach (Transform child in t)
{
Transform ct = FindChild(name, child);
if (ct != null)
return ct;
}
return null;
}
public void initialize()
{
this.MaxVal = maxVal;
this.CurrentVal = currentVal;
}
}
Something like this might work:
transform.parent.gameObject.GetComponentInChildren(...)
Yes. The ... were supposed to mean "you know what to insert here" :)
yh but when i put the $$anonymous$$eyWord BarScrpit it says that it is not a valid System.Type
So do you want to find HealthBar or a component on HealthBar? In the latter case, can you show its components?
I want do find a component that is a script called BarScript that is on the HealthBar
I really thought something like this would have worked:
BarScript script = transform.parent.gameObject.GetComponentInChildren<BarScript>();
I don't know why it doesn't, i would have to try it out myself.
$$anonymous$$aybe you can just add a public variable for the Healthbar to the player script and drag it in there in the editor like Unity wants us to do :)
Couldn't you just try creating a GameObject variable, healthBar, and then referencing it to get the component?
public GameObject healthBar;
healthBar.GetComponent<BarScript>();
//more code
Or you can use
GameObject.FindGameObjectWithTag("HealthBar").GetComponent();
if you use this way, then don't forget to tag your health bar as "HealthBar"
Your answer
Follow this Question
Related Questions
Easy Short kill score script not working 0 Answers
How do I make a x move and y move parameter 0 Answers
Problem when I call fonction with child class 1 Answer
Adding a Highscore to game 1 Answer
Help! Script won't work. 1 Answer