- Home /
Duplicate Question
Trying to access a variable from another script attached to same object.
oh boy... let me start by saying I have only been using Unity3d for about 2 weeks now and that my C# skills are not so... well... sharp. I am working on a school project.
I am having a hell of a time references a variable in one script with another script. The 2 scripts are even on the same object so it blows my mind that the program has such a hard time handling this. I KNOW that there are already tons of posts on this subject, I have poured over a lot of them and tried to use the code from the answers but something just isn't working right or I'm not interpreting something right. I was hoping for a specific example using my variables,script-names and code.
I am using Unity 3.5.5 and programming in C#. My first script is EnemyHealth.cs and contains the following using UnityEngine; using System.Collections;
public class EnemyHealth : MonoBehaviour {
public int maxHealth = 10;
public int currentHealth = 10;
public float healthBarLength;
// Use this for initialization
void Start () {
healthBarLength = Screen.width / 2;
}
There is more there but it seems irrelevant as it is mostly GUI stuff. The variable I want to use in script 2 is the currentHealth stat. I have named script 2 EnemyDeath.cs, it is attached to the same game object and want to get it to pull the current health and use an if statement to detect if the current health <= 0 then "whatever" happens... (it turns red, it falls over)... but whatever I try I can not get the variable to pass along the info. Someone please give me something in a format where I could just cut and paste it into my code as I am just not savvy enough to transmute any "examples".
Also - please don't just paste in "http://docs.unity3d.com/Documentation/ScriptReference/index.Accessing_Other_Game_Objects.html" as the answer; as that is incredibly unhelpful(to someone of my skill-level) and when I have enough karma I will go around and thumbs-down those posts into oblivion.
negative voting also removes karma from you, just be aware.
$$anonymous$$aybe this tutorial from UnityGems can help : http://unitygems.com/script-interaction1/
$$anonymous$$ake some test scenes, and play around with GameObject.Find and GetComponent
http://docs.unity3d.com/Documentation/ScriptReference/GameObject.Find.html
http://docs.unity3d.com/Documentation/ScriptReference/GameObject.GetComponent.html
ps. you cannot downvote my comment !
Not sure if you are trying to troll me but since no-one else has answered yet I'll address the things you posted. I tried working with the first tutorial (the unity gems). In the beginning I tried to just modify my code to be similar (even though it required changing my public ints to private and changing a lot of things I would prefer not to if it could be avoided. In the end I still ran into error messages so I took your advice and made a completely blank test-scene and followed the tutorial to a T and still get an error "Assets/ScriptA.cs(20,33): error CS0122: `ScriptB.varB' is inaccessible due to its protection level" which is the same message I got when trying to modify my script. This is why just pasting in links is not very helpful - in the end I've only ended up with more errors and questions than I had in the beginning.
No, not trolling (check my profile page and my karma), just trying to help without doing all the work for you. This is a concept you just have to learn to understand.
The easiest way would just make currentHealth a public static variable, but I am not keen on static things and learning GetComponent will open many doors.
This video should explain alot : http://www.unity3dstudent.com/2010/07/beginner-b17-tweaking-components-via-script/
Or I can describe a scenario :
Imagine I have a GameObject in my scene called Level$$anonymous$$anagerObject, and attached to that object is a script called Level$$anonymous$$anagerScript, let's say that has a public variable on it called gameTime.
Now from the PlayerScript, how to find, access and/or modify gameTime? First you need to find the GameObject Level$$anonymous$$anagerObject
var obj : GameObject = GameObject.Find( "Level$$anonymous$$anagerObject" );
ok, so that stores a reference to the GameObject, now how about the script?
var objScript : Level$$anonymous$$anagerScript = obj.GetComponent( Level$$anonymous$$anagerScript );
now you have a reference to the script. SO how to read and write to that variable?
var getGameTime : float = objScript.gameTime;
There you have it. I strongly suggest making a new scene/project, just have 2 objects and try and get them to talk to each other first, then when you are comfortable then implement what you have learned into your big project =]
If you need any more info, we are here to help, not troll, ok. That kind of thing gets wiped out pretty quickly here.
btw, the error message says it all : error CS0122: `ScriptB.varB' is inaccessible due to its protection level"
what is its protection level? $$anonymous$$y guess is that varB is private.
It looks like this question has already been answered before. :)
Answer by AlucardJay · Jan 21, 2013 at 08:01 AM
Here are some links I strongly suggest to all new users :
Start at the bottom and work up : http://www.unity3dstudent.com/category/modules/essential-skills/
Start at the bottom and work up : http://www.unity3dstudent.com/category/modules/beginner/
this is the YouTube link for the above as one playlist : http://www.youtube.com/watch?v=-oXYHNSmTxg&list=PL27B696FB515608D2&feature=plcp
That is good to get started. Then start with a small tutorial, this is a simple 2D space shooter : http://www.unityjumpstart.com/ProofOfConcept_1/ : click on the videos part1.mp4 part2,3,4 =]
I found another by Eric : http://wiki.unity3d.com/index.php?title=2DShooter : http://forum.unity3d.com/threads/7883-2D-shooter-tutorial
By then you should be getting the hang of things and starting to have ideas of your own. When you decide what kind of game you want to make, then look at each part you'll need. For example, if you want to make some terrain then walk around it with a character : http://cgcookie.com/unity/2011/12/05/introduction-to-character-controllers/
Basically then just search for tutorials, there are many out there, either written or on youtube.
the Unity Wiki tutorials : http://wiki.unity3d.com/index.php/Tutorials
A big list of tutorials : http://answers.unity3d.com/questions/12321/how-can-i-start-learning-unity-fast-list-of-tutori.html
A very helpful 'site, all in C# : http://unitygems.com/
Helpful page with information on using Built-In Arrays and Lists (you'll need this later!) : http://www.unifycommunity.com/wiki/index.php?title=Which_Kind_Of_Array_Or_Collection_Should_I_Use?
The unity wiki link above is very handy with lots of scripts and shaders too (just check out all the links down the left, and the tabs along the top : http://wiki.unity3d.com/index.php/Scripts )
http://answers.unity3d.com/questions/148211/list-of-frequently-asked-beginners-questions.html
http://forum.unity3d.com/threads/132628-How-to-help-the-Absolute-Beginner
If you know what kind of game you want to make, edit your question and write there what you are thinking of, then there may be a tutorial out there for that, Happy Coding =]
Wow... nice list of links... I'm actually already watching some of the suggested ones (BurgZerg and Walkerboys) and find them very useful but will absolutely bookmark this list and delve deeper.
Thanks Bunny83, I appreciate the thought. Joshua $$anonymous$$, I really hope this gets you started. Fattie, sorry for perpetuating a common question, I need to find a link to one of fafases answers for GetComponent stuff. fafase, thanks also!
Just to say this is an awesome answer and of great help to me. I've been struggling to get to grips with the beginnings of Unity and answers along of the lines of 'RTF$$anonymous$$' are NOT helpful. I, for one, have read the relevant manual bits about 10 times over! It's not always helpful for your situation!
Follow this Question
Related Questions
Changing class data with a reference? 2 Answers
Problem with accessing static variables 1 Answer
How to pass variables from one object in one scene to another object in another scene? 3 Answers
Distribute terrain in zones 3 Answers
Creating Dropdown menue for variables in the Inspector using C# 1 Answer