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 /
avatar image
0
Question by George-B · Jul 22, 2016 at 08:48 PM · unity 5gameobjecttransformchild objectfill

Can You Convert a Transform into an Image?

Hello! I am making a video game, where the player moves around the screen and presses the space bar to fire harpoons at fish. Each fish has a health bar, and I want to access the fill amount of the health bar when the harpoon touches the fish.

I have tried to access the health bar child of the fish, but I keep getting errors. What is the correct way to access a child (specifically an Image) of a parent GameObject. How do I change its fillAmount? Thanks in advance- George

Here is my code-
harpoonScript

 using UnityEngine;
 using System.Collections;
 using UnityEngine.UI;
 
 public class harpoonScript : MonoBehaviour {
 
 // Public variable 
 public int speed = 6;
 private Rigidbody2D r2d;
 public Text FishLabel;
 public int fishKillCount = 0;
 
 public Transform fishBar;
 public Image fishBarFill;
 
 // Function called once when the bullet is created
 void Start () {
     // Get the rigidbody component
     r2d = GetComponent<Rigidbody2D>();
 
     // Make the bullet move upward
     float ySpeed = 0;
     float xSpeed = -8;
 
     Vector2 newVelocity = new Vector2(xSpeed, ySpeed);
 r2d.velocity = newVelocity;
 
 }
 
 void OnTriggerEnter2D(Collider2D other) //hero hits side of enemy
     {
 
       fishBar = this.gameObject.transform.GetChild(3);
       fishBarFill = fishBar;
 
       if (fishBar.fillAmount > 0) {
 
         fishBar.fillAmount = fishBar.fillAmount - 0.5;
   }
 
   else {
     string fishStringfromText = FishLabel.text;
              int fishIntfromText;
              fishIntfromText = int.Parse(fishStringfromText);
 
   ++fishIntfromText;
 
   FishLabel.text = fishIntfromText.ToString();
 
        Debug.Log("GameObject found, reference is not null");
        Destroy(other.gameObject.GetComponent<Collider2D>()); //Remove collider to avoid audio replaying
             other.gameObject.GetComponent<Renderer>().enabled = false; //Make object invisible
             Destroy(other.gameObject, 0.626f); //Destroy object when audio is done playing, destroying it before will cause the audio to stop
     Destroy(GameObject.Find("harpoon_00001(Clone)"));
   }
 }
 
 }

PS- Sorry if my question is too vague, or you don't have enough information. Just tell me, and I can add more to my question :)

Comment
Add comment
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

2 Replies

· Add your reply
  • Sort: 
avatar image
1
Best Answer

Answer by smnerat · Jul 23, 2016 at 05:06 AM

You didn't post the error so I'm not sure what your problem is, but I would guess its due to several misunderstanding at line 33.

At line 33, you are trying to get the health bar, which is an image, by searching for a transform as if it were the child of the harpoon, not the fish.

With that said, to get the transform itself, try this:

 void OnTriggerEnter2D(Collider2D other) { 
        fishBar = other.transform.GetChild(3);
 
        etc.....
 }

Now you should have a reference to the transform that has an Image component on it, but you still need to access the actual Image component before you can do anything.

 void OnTriggerEnter2D(Collider2D other) { 
        fishBar = other.transform.GetChild(3);
        fishBarFill = fishBar.gameObject.getComponent<Image>();

        fishBarFill.fillAmount = 0.5f;
 }

This general concept applies to pretty much everything in Unity. First, get a reference to the transform or gameObject that the component is on. Then get whatever component you need (transform, collider, material, renderer, script, text, etc).

Comment
Add comment · 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
2

Answer by josehzz112 · Jul 23, 2016 at 06:36 AM

Hello I think I spot some errors, lets go step by step.

  1. Make sure that the Image component you want to access has Image Type = Filled on the Inspector.

  2. You are getting a Transform component and saving that on an Image variable. (First error).

  3. Because fishBar is a Transform variable it doesn't have a fillAmount parameter. (Second error).

Here's the fixed code, make sure you have everything assigned on the inspector before running it.

 using UnityEngine;
 using System.Collections;
 using UnityEngine.UI;
  
 public class harpoonScript : MonoBehaviour {
  
 // Public variable 
 public int speed = 6;
 private Rigidbody2D r2d;
 public Text FishLabel;
 public int fishKillCount = 0;
  
 public Transform fishBar;
 public Image fishBarFill;
  
 // Function called once when the bullet is created
 void Start () {
      // Get the rigidbody component
      r2d = GetComponent<Rigidbody2D>();
  
      // Make the bullet move upward
      float ySpeed = 0;
      float xSpeed = -8;
  
      Vector2 newVelocity = new Vector2(xSpeed, ySpeed);
      r2d.velocity = newVelocity;
  }
  
 void OnTriggerEnter2D(Collider2D other) //hero hits side of enemy
 {
        fishBarFill = this.gameObject.transform.GetChild(3).GetComponent<Image>();
  
        if (fishBarFill.fillAmount > 0) {
          fishBarFill.fillAmount = fishBarFill.fillAmount - 0.5;
        }
        else {
          string fishStringfromText = FishLabel.text;
          int fishIntfromText;

          fishIntfromText = int.Parse(fishStringfromText);
          ++fishIntfromText;
  
          FishLabel.text = fishIntfromText.ToString();
  
         Debug.Log("GameObject found, reference is not null");
         Destroy(other.gameObject.GetComponent<Collider2D>()); //Remove collider to avoid audio replaying
         other.gameObject.GetComponent<Renderer>().enabled = false; //Make object invisible
         Destroy(other.gameObject, 0.626f); //Destroy object when audio is done playing, destroying it before will cause the audio to stop
         Destroy(GameObject.Find("harpoon_00001(Clone)"));
         }
  }
  }



Comment
Add comment · Show 3 · 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 George-B · Jul 23, 2016 at 06:34 PM 0
Share

@josehzz112- I inserted this new fixed code, but now the console gives me an error like this-

UnityException: Transform child out of bounds harpoonScript.OnTriggerEnter2D (UnityEngine.Collider2D other) (at Assets/Levels/Scripts/harpoonScript.cs:33)

What does this error mean in my case, and how do I fix it? (Is it because 3 might not be the index of the child I want to access?)

avatar image smnerat George-B · Jul 23, 2016 at 06:45 PM 1
Share

Yes, your assu$$anonymous$$g you hit the parent object. Does each child transform have a collider attached? You could be hitting anyone of those or even something else in the scene.

I would remove all colliders from your children and have just one on the parent object. Then I would also tag your child object that you want to access and search for that. Here's untested code:

         Transform[] transforms = other.gameObject.GetComponentsInChildren<Transform>();    
         foreach (Transform t in transforms) {
             if (t.tag == "FishTag") {
                 fishBarFill = t.gameObject.getComponent<Image>();
                 fishBarFill.fillAmount = 0.5f;
             }
         }
avatar image George-B smnerat · Jul 23, 2016 at 07:19 PM 0
Share

Okay. I've got it now! Thanks for all your help :)

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

5 People are following this question.

avatar image avatar image avatar image avatar image avatar image

Related Questions

Syncing Position and Rotation data in ECS tests? 0 Answers

Instantiating a new gameObject as a child of a different gameObject 2 Answers

Change gameobjects position if it's already used by a different gameobject? 1 Answer

Unity child gameobjects spawning with incorrect transforms over network, any ideas? 0 Answers

How Should I Get a List of Child Objects 2 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