I’m new to Unity and I’m currently working on a project where I need to access a Game Object from one script in another script. Specifically, I have a script attached to my player Game Object that needs to access the score Game Object in order to update the player’s score.
I’ve tried using Game Object. Find and Get Component, but I’m not having any luck. Can someone please provide an example of how to properly access a Game Object from another script in Unity? Any help would be greatly appreciated!
Declare a public variable of type GameObject in the script you want to be able to access it, a slot will appear in the script’s inspector. Then in the editor just drag and drop the GameObject into the slot.
GameObject.Find() should work fine, in case you want to look for the object at runtime. What exactly have you tried?
GetComponent() will return a Component, not a GameObject, but you can access the GameObject that owns the component like this:
Referencing variables, fields, methods (anything non-static) in other script instances:
REMEMBER: it isn’t always the best idea for everything to access everything else all over the place. For instance, it is BAD for the player to reach into an enemy and reduce his health.
Instead there should be a function you call on the enemy to reduce his health. All the same rules apply for the above steps: the function must be public AND you need a reference to the class instance.
That way the enemy (and only the enemy) has code to reduce his health and simultaneously do anything else, such as kill him or make him reel from the impact, and all that code is centralized in one place.