Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
12 Jun 22 - 14 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 Extranomy · Feb 14, 2016 at 05:45 PM · scripting problemscripting beginnerscriptingbasicsscript erroraccessing from any script

Accessing script from another object

Hello,

I have script attached to Player and another script attached to multiple Enemies
Anyway, I'm not sure how to access variables from Enemy script so Player can take damage, get experience and etc.
Writing public Enemy myEnemy; doesn't work in Player script and I really don't know how to fix it. :(

EnemyScript

 using UnityEngine;
 using System.Collections;

 public class Enemy : MonoBehaviour{
     
     public int Health;
     public int Damage;
     public int Experience;
 }

Player Script:

 using UnityEngine;
 using System.Collections;
 using UnityEngine.UI;

 //------------------------------------------------------------------------------------
 public class Player{
 
     //Player attributes.
     private int Health;
     private int Mana;
     private int ReqExp;
     private int CurrExp;
     private int Level;
     private int Damage;
 
     //Set values of player attributes.
     public void SetValues(int HP, int MP, int R_EXP, int C_EXP, int LVL, int DMG){
         Health = HP;
         Mana = MP;
         ReqExp = R_EXP;
         CurrExp = C_EXP;
         Level = LVL;
         Damage = DMG;
     }
 
     //Player take damage from enemy and lose DMG of health points.
     public void GetDamage(int DMG){
         if (Health > 0) {
             Health -= DMG;
         }  

         if(Health <= 0;){
             GameObject.Destroy (GameObject.FindGameObjectWithTag ("Player"));
             Debug.Log ("You're dead!");
         }
     }

     public int GetHealth(){
         return Health;
     }
 }
 //------------------------------------------------------------------------------------

 public class PlayerScript : MonoBehaviour {
 
     public Player myPlayer;
     public Enemy myEnemy;  // <-- I'm doing it wrong, yes?

     public float distance; //Distance between player and enemy.
     public Text myHealthText; //Health text.
 
     void Start(){
         //(Health, Mana, ReqExp, CurrExp, Lvl, Damage).
         myPlayer.SetValues (100, 100, 130, 0, 1, 10);
     }
 
     void Update () {
         distance = Vector3.Distance(gameObject.transform.position, 
         GameObject.FindGameObjectWithTag("Enemy").transform.position);

         if (distance <= 3) {
             myPlayer.GetDamage (myEnemyScript.Damage); //Get damaged by enemy.
             StartCoroutine (WaitAfterHit ()); //Wait few seconds after hit.
         }
         myHealthText.text = "Health " + myPlayer.GetHealth().ToString(); //Show player health.
     }
         
     IEnumerator WaitAfterHit(){
         yield return new WaitForSeconds (5);
     }
 }
   }





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

Answer by dan5071 · Feb 14, 2016 at 06:00 PM

You've got it right so far in that you're referencing the Enemy script, but you will also need to associate that script with the correct enemy game object with that script attached. Here are some changes to the code that should allow you to access methods in the script that is attached to your enemy

     public Player myPlayer;
     public GameObject myEnemy;  // Create a public reference to the enemy game object.
     public float distance;
     public Text myHealthText;
 
     private Enemy _enemyScript; // Reference to the script attached to "myEnemy" object.
 
     void Start()
     {
         myPlayer.SetValues (100, 100, 130, 0, 1, 10);
 
         // Find the Enemy script attached to "myEnemy"
         _enemyScript = myEnemy.GetComponent<Enemy>();
     }

I would have continued with more modifications but I'm not sure where your variable "myEnemyScript" on line 62 is defined, so I don't want to confuse you. But if you proceed by trying to access the methods in the Enemy script through "_enemyScript" as I defined it, then things should work the way you want them to.

It's also worth mentioning that using GameObject.FindGameObjectWIthTag() in the update routine is a very, very bad idea as this becomes quite computationally expensive searching through all game objects in the scene every single frame. A more optimized approach would be to replace it with myEnemy.transform.position since I declared the public game object myEnemy in the modifications above. This way, you won't search through all the game objects in your scene every frame just to check the distance between the player and the enemy. In the early stages of your project it might not be a big deal, but this will certainly become a problem as you add more objects to the scene and have more scripts running and such.

Comment
Add comment · Show 2 · 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 duke_meister · Jun 06, 2018 at 11:03 AM 0
Share

Is this the same as making a public variable of type Enemy (like above) then dragging the Enemy GameObject onto the Enemy slot from the hierarchy?

avatar image Delvarn · Aug 31, 2020 at 09:39 PM 0
Share

Thanks! Strang ehow I've accessed scripts with declaring the gameobject before, but this fixed my problem, thanks.

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

6 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Making a game where objects need to be shot off of a surface. level complete when all objects are shot off. difficulty in scripting for level completion. 0 Answers

Getting weird error message!?!?!? 1 Answer

this script is missed up help? 1 Answer

How can I temporary increase the size of an object? 2 Answers

Why is my script not working? 1 Answer


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