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
8
Question by sjayb2k · Feb 15, 2010 at 07:15 AM · variableaccesscommunicationoafa

How do I access information (eg, variables, functions, properties) on other objects from inside a script?

I have been running into this issue for a while now and can't seem to figure it out.

I have a player object. I also have an enemy objects that I am spawning through a prefab. I want the enemy objects to be able to access information about the player's script such as how much health it has left. how can I accomplish this in C#?

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
22
Best Answer

Answer by duck · Feb 15, 2010 at 10:06 AM

There are many many ways in unity for objects to access each other's components, scripts, functions and variables. Start reading about it at this manual page:

Controlling GameObjects Using Components

Also see this answer which gives more detail about creating "dragged references":

How can I access other scripts and their functions?

In your particular case, if you only have a single "Player" at one time, you could use "FindObjectOfType" to find the player script instance at runtime, when the enemy is created. FindObjectOfType is ideal when you know the script you're looking for is the only one of its kind in your scene. It's relatively slow to execute, so we store the reference in a variable in Start() and just use the variable later.

I'm assuming you have a script on your player, and for this example I'm going to assume it's called "PlayerScript". Whatever it's called, you need to use the exact script name where I write "PlayerScript":

This would be in your enemy script:

private PlayerScript player;

void Start() { // find the current instance of the player script: player = FindObjectOfType(typeof(PlayerScript)); }

You can then access public variables on the player's script, from inside your enemy script, using code like this:

player.health

And call functions on the player's script like this:

player.ApplyDamage(20);

You can also access the Game Object to which the player script is attached:

player.gameObject

And other built-in component references:

player.transform
player.renderer
player.collider
player.rigidbody
//..etc

As well as any other component type which doesn't have a built-in reference:

SomeOtherComponent c = player.GetComponent<SomeOtherComponent>();

(where "SomeOtherComponent" is the name of another component or script)


If there is more than one object of a certain type, and you want to get references to all of them, you can use the very similarly named "FindObjectsOfType" function. This differs in that it returns an Array of the type of object that you specify. For example, if you have 10 enemies in your scene, each with "EnemyScript" attached, you could use:

EnemyScript[] enemies = FindObjectsOfType<EnemyScript>();

You now have an array containing references to all the current instances of the enemy scripts. You can then iterate through them using a foreach loop:

foreach (EnemyScript enemy in enemies)
{
    // do whatever with each 'enemy' here
}
Comment
Add comment · Show 7 · 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 sjayb2k · Feb 15, 2010 at 03:15 PM 0
Share

Thanks for the response. Is there a way to do something similar but with Objects that there are more than one of. For example check the hitPoints of an enemy?

avatar image duck ♦♦ · Feb 15, 2010 at 05:27 PM 0
Share

Yes it's possible. I've updated the answer to include this information.

avatar image sjayb2k · Feb 16, 2010 at 05:57 AM 0
Share

Thanks again. you were a huge help.

avatar image sanks007 · Jul 31, 2013 at 05:12 AM 0
Share

thanks for the answer.. finally the problem solved.

avatar image Jamora · Oct 08, 2013 at 06:14 PM 0
Share

Fixed the links so everyone I steer to this page won't be confused.

Show more comments
avatar image
2

Answer by Ricardo · Feb 15, 2010 at 07:55 AM

What you want to learn about is public properties in C#, getters and setters.

Comment
Add comment · Show 6 · 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 sjayb2k · Feb 15, 2010 at 08:17 AM 0
Share

Thanks for the quick response.

I am familiar with how getters and setters work and already had a public getter for this purpose. I am getting an error: NullReferenceException: Object reference not set to an instance of an object.

From my understanding that means that I haven't set my player correctly

I declared the player by saying

Player playerCharacter;

however when I try to then set the player I get issues playerCharacter = GameObject.Find("Player");

this line gives me the error saying I can't convert UnityEngine.GameObject to Player

how can I set this correctly?

avatar image Ricardo · Feb 15, 2010 at 08:22 AM 0
Share

That would be C# type casting and type conversions that you need to read about.

avatar image sjayb2k · Feb 15, 2010 at 08:37 AM 0
Share

When I try to cast the object by saying playerCharacter = (Player)GameObject.Find("Player"); I still get an issue where it can't convert UnityEngine.GameObject to Player.

Is there anything special that I have to do to declare Player as a variable in the Enemy script? It is prefab.

avatar image sjayb2k · Feb 15, 2010 at 09:02 AM 0
Share

The player class inherits from a class called Human. Human is the class that inherits from $$anonymous$$onoBehaviour.

avatar image Ricardo · Feb 15, 2010 at 11:27 AM 0
Share

Ah, my bad (replied early in the morning) What you're actually getting with GameObject.Find is a game object by that name. You would then need to obtain the Human component in that game object, using returnedObject.GetComponent();

Show more comments

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

3 People are following this question.

avatar image avatar image avatar image

Related Questions

Access variable from another script? Health! 3 Answers

Collision object and access to a script variable? 1 Answer

My script accessing a variable from another script recieves an error 1 Answer

Cannot access a variable in another Script. 2 Answers

Can I make variables visible to other scripts without making them visible in the Inspector? 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