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 S1ayer450 · Oct 16, 2016 at 07:20 AM · c#2d-platformercollision2d5.3

Subtract value from one script to another

Hello community

I've been having some difficulties with trying to communicate with my health int from character to subtract from the value of setEnemyDamage int. What I'm trying to pull off is setting the damage from an Obstacle quickly in public so I can change the value per each scene level for more of a challenge as the player progresses. My playerHealth seems to pick up health int outcome, but when I go over top the Obstacle trigger collider it appears that it has it's own int and doesn't subtract from character health script. I'm using 5.3 version as this is a school project. If any answers to this question soon would be greatly appreciated!

Obstacle script

 using UnityEngine;
 using System.Collections;
 using UnityEngine.SceneManagement;
 
 public class Obstacle : MonoBehaviour {
 
     public GameObject playerObject; 
     public int setEnemyDamage;
     private Character ScriptAccess;
     private int playerHealth;
 
     // Use this for initialization
     void Start () {
 
         ScriptAccess = playerObject.GetComponent<Character>();
 
         playerHealth = ScriptAccess.health;
 
         Debug.Log(playerHealth);
 
     }
     
     // Update is called once per frame
     void Update () {
     
     }
 
     //Avoids destroying player on collision, also destroys projectiles
     void OnTriggerEnter2D(Collider2D c)
     {
 
         if (c.gameObject.tag == "Projectile") {
 
             Destroy (c.gameObject);
  
             }
 
         if (c.gameObject.tag == "Player")
         {
             playerHealth -= setEnemyDamage;
             Debug.Log(playerHealth);
         }
     }
 }
 

Character script

 using UnityEngine;
 using System.Collections;
 using UnityEngine.SceneManagement;
 
 public class Character : MonoBehaviour {
     
     public Rigidbody2D rb;                    // Public. Accessible through Inspector. Must drag object/component into Script.
     
     public float jumpForce;                    // Pubilc. Let's user update value through Inspector.
     
     // Handles movement and jumping
     public int health;                         // Player Health
     public bool isGrounded;                    // Used to see if character is on the floor, platform, etc...
     public LayerMask isGroundLayer;    // Used to list what is Ground
     public Transform groundCheck;        // Used to check ground collision
     public int speed;                               // Used to give character a speed.
     public int coinCollection;          // Player coins collection
     public int powerCoins;              // Player power up coins
 
     // Handles animations
     public Animator anim;                        // Used to access the animator controller
     int state;                                            // Used to change state of character
 
     // Handles projectiles
     public Transform projectileSpawnPoint;   // Whatever the teacher did here
     public Rigidbody2D projectilePrefab;     // I was forced to write this
 
     // Controls facing direction
     public bool facingRight;
 
     // Use this for initialization
     void Start () {
 
         // Link component to variable to be used later.
         rb = GetComponent<Rigidbody2D> ();
         anim = GetComponent<Animator> ();
         
         // Check that GetComponent worked.
         // Works if there is a Rigidbody2D on the object the Script is linked to.
         
         if (!rb) // Is there no Rigidbody2D.
             Debug.Log ("No Rigidbody2D attached.");
         
         if (!anim) // Is there no Animator.
             Debug.Log ("No Animator attached.");
     }
     
     // Update is called once per frame
     void Update () {
     
         if (health <= 0)
         {
             health = 0;
             Destroy(gameObject);
 
         }
 
         // Check if character is on ground
         isGrounded = Physics2D.OverlapCircle (groundCheck.position, 0.2f, isGroundLayer);
         
         // Check if Space is pressed.
         if (Input.GetButtonDown ("Jump") && isGrounded) {
             // Player wants to Jump.
             // Make character jump.
             Debug.Log("Jump");
 
             anim.SetTrigger ("Jump");
 
             // Use Rigidbody to move character
             rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
         }
         
         // Check if Fire is pressed.
         if (Input.GetKeyDown (KeyCode.LeftControl)) {
             // Player wants to Fire.
             // Make character fire.
             fireProjectile();
         }
             
         // Make character move left or right, if grounded
         // GetAxisRaw returns -1,0,1
         // GetAxis returns -1->1
         float moveValue = Input.GetAxisRaw ("Horizontal");
         
         // Make character move left or right.
         rb.velocity = new Vector2 (moveValue * speed, rb.velocity.y);
         
         // Change state parameter
         anim.SetFloat ("Move", Mathf.Abs (moveValue)); 
 
 
         // Check if character should look Left or Right
         if (     (moveValue > 0 && !facingRight) ||
             (moveValue < 0 && facingRight))
             flip ();
 
         // Check if player is on ground, if so Jump
 
         anim.SetBool ("IsGrounded", isGrounded);
 
     } // Closes Update()
     
     // Function to flip Character in direction it's moving
     void flip()
     {
         // Toggle facingRight variable
         facingRight = !facingRight;
         
         // Make a copy of old scale
         Vector3 scaleFactor = transform.localScale; // Scale is (1,1,1);
         
         // Flip the scale
         scaleFactor.x *= -1; // Changed to (-1,1,1)
         
         // Update the scale to flipped value
         transform.localScale = scaleFactor;
     }
 
     void fireProjectile()
     {
         // Make character fire.
         Debug.Log ("Pew Pew");
         // Change state parameter
         anim.SetTrigger ("Attack");
 
         if (facingRight) {
             Instantiate (projectilePrefab, projectileSpawnPoint.position,
                 Quaternion.Euler (new Vector3 (0, 0, 0)));
         } else if (!facingRight) {
             Instantiate (projectilePrefab, projectileSpawnPoint.position,
                 Quaternion.Euler (new Vector3 (0, 180.0f, 0)));
         }
     }
 
 
     // Collectiable items, and stored into player database.
     void OnTriggerEnter2D(Collider2D col)
     {
         if (col.gameObject.tag == "Collectible")
         {
             coinCollection++;
             Destroy(col.gameObject);
             Debug.Log("A COIN!");
         }
         if (col.gameObject.tag == "PowerCoin")
         {
             powerCoins++;
             Destroy(col.gameObject);
             Debug.Log("POWER UP!");
         }
     }
 
 }
 
 

Thank you for taking the time to read.

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

1 Reply

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

Answer by Gothic_Anatomist · Oct 16, 2016 at 09:09 AM

Instead of referencing the variable in your character script directly from your obstacle, you could create a method in the charaacter script to change the value - such as:

 public void DecreaseHealth (int damage) 
 {
     health -= damage;
     Debug.Log(health);
 }

The you call it from your obstacle script and pass in the setEnemyDamage value:

 if (c.gameObject.tag == "Player")
          {
              scriptAccess.DecreaseHealth (setEnemyDamage);
          }


I hope that helps :)

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 S1ayer450 · Oct 16, 2016 at 03:55 PM 0
Share

Ahh C!!! That makes better sense now! Thank you

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

Multiple Cars not working 1 Answer

Distribute terrain in zones 3 Answers

problem Getting AI projectile to collide with player 0 Answers

How do I know if collision is from right or left when using a Tilemap Collider 2D 0 Answers

[HELP!] Run in opposite direction on wall collision 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