Cannot figure out GetComponent for the life of me
I've looked at dozens of tutorials and posts around here, but I simply cannot wrap my head around how GetComponent works and I'm beginning to lose my mind. I have two scripts, one called PlayerHealth and one called HealthBarScript. I need to access the health variable from PlayerHealth and use it to control the fill amount of a sprite in HealthBarScript. Nothing I've tried has worked. If somebody could break it down super simply for me it would be much appreciated. Also, I am an absolute beginner so sorry if my code looks like trash.
PlayerHealth -
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(AudioSource))]
public class PlayerHealth : MonoBehaviour {
public static int health = 100;
public AudioSource playerAudio;
public AudioClip GameOver;
private bool deathDone;
// Use this for initialization
void Start () {
playerAudio = GetComponent<AudioSource>();
health = 100;
deathDone = false;
}
// Update is called once per frame
void Update ()
{
if (health <=0 && !deathDone)
{
health = 0;
Debug.Log ("Mission Failed.");
playerAudio.PlayOneShot (GameOver, 1.0f);
deathDone = true;
}
}
// If the player hits a KillBox
void OnCollisionEnter2D(Collision2D coll)
{
if (coll.gameObject.tag == "KillBox")
{
health = 0;
}
if (coll.gameObject.tag == "EnemyProjectile")
{
health -= 10;
}
}
}
HealthBarScript -
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class HealthBarScript : MonoBehaviour {
public GameObject player;
public Image HealthSprite;
// Use this for initialization
void Start ()
{
GameObject thePlayer = GameObject.Find("thePlayer");
PlayerHealth health = player.GetComponent<PlayerHealth>;
HealthSprite = GetComponent<Image>();
}
// Update is called once per frame
void Update ()
{
HealthSprite.fillAmount = PlayerHealth.health/360;
}
}
you're maybe not a million miles away...
line 14 of HealthBarScript
should probably read:
player = GameObject.Find("thePlayer");
you're getting a reference to something named "thePlayer", but doing nothing with it. the next line should be using that. should ;)
on line 15 of HealthBarScript
, you get the reference to the PlayerHealth
component but don't do anything with it. when you use the health
variable later on, since you've made it static
, you're not referencing an instance of it, but the only one (shared by all GameObejcts)
to fix this, declare health outside of Start()
is there an Image
component attached to the same GameObject as HealthBarScript
? that's what line 16 is getting.
Answer by meat5000 · Feb 11, 2016 at 02:06 PM
All entries in the Inspector when you click on an object is a Component. Transform, Animator, Mesh, scripts call all be added to an Object with AddComponent at runtime (ok not Transform as its already added by default).
In a script, to use such a component, you first create an empty placeholder variable for it. The 'type' of this variable is the Component type.
public ComponentType myComponent;
public AudioSource playerAudio;
Its EMPTY. You need to fill it up with something real.
Using GetComponent you access a reference to the component you are trying to access. The 'gameObject.' field before GetComponent defines the object that the GetComponent call takes the component from.
gameObject.GetComponent
refers to the object on which that code is attached. GetComponent<>()
without the 'gameObject.' is the same as gameObject.getComponent<>()
its just a shortcut.
someOtherObject.GetComponent
accesses the component on that other object.
void Start()
{
myComponent = GetComponent<ComponentType>();
playerAudio = GetComponent<AudioSource>();
//So here your empty variables are provided with a reference to the actual components and so you can interact with them at runtime.
So, you make you variable in the class so it exists through the script (instead of declaring in, say, Start() in which it will only exist within Start() ). You then place your GetComp call within start, as above. Now you can use the . (dot) operator to access members of that component.
If 'myVariable' is a variable within ComponentType, you can access it through your reference variable after GetComponent has cached the reference.
myComponent.myVariable;
Awesome, thanks for the in-depth help! I'll give it a shot and see what happens.
Your answer
Follow this Question
Related Questions
Question on Textbox Margin and Size limitations,Scaling margin on text box 0 Answers
Create an easy craft system 1 Answer
Problems with positioning GUI rectangle and GameObject 0 Answers
How do I simulate relative movement? 0 Answers
I have prefabs that should be referencing different GameObjects, but they all refer to the same one. 0 Answers