Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
  • Help Room /
avatar image
0
Question by Soapmac72 · Feb 11, 2016 at 01:58 PM · guigameobjectreferencing

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;
     }
 }
 
Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image gjf · Feb 11, 2016 at 02:01 PM 2
Share

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.

1 Reply

· Add your reply
  • Sort: 
avatar image
0

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;



Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Soapmac72 · Feb 11, 2016 at 10:44 PM 0
Share

Awesome, thanks for the in-depth help! I'll give it a shot and see what happens.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

4 People are following this question.

avatar image avatar image avatar image avatar image

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


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges