Your script has a bunch of unnecessary lines of code in it. Additionally, ‘Real’ is an awful Object name. Classes define objects, and objects are things, so their names should always be nouns, whereas the word Real is an adjective. Your script names should be as descriptive as possible so that others reading your code know what they mean. I once ran across a script named ‘TTTTTT’…no kidding. What in the world is that?
Anyway, back to your question. First off, instead of dragging the GameObject into the GameObject variable, and then getting the Real component at runtime (and at least twice per frame when done in OnGUI), you should just drag the GameObject into the Real field. Unity is smart enough to link up the script instead of the GameObject. If you must get it at runtime, you should use a separate method to do that work for you.
Finally, the same goes for variable names as does class names; they should be meaningful. The variable selected1 doesn’t tell us anything about what that variable stores, and only through seeing how you’ve used it can we tell what type it is. Boolean values should, in good coding practice, always be named is{Something}, like isActive, isBlue, isMoving, etc. This tells anyone reading your code that it is a boolean value, and when it is true it ‘is active’. Unity doesn’t do this, so if you’re when in Rome type, then follow their lead. But be aware that there are coding conventions for each language, and if you don’t adhere to them then expect to get an earful from colleagues at some point.
Example using Real
var real : Real;
function OnGUI ()
{
if (GUI.Button(Rect (10,10,100,75), "I am a button") && real.selected1)
testObject.renderer.material.color = Color.yellow;
}
Example of Method Returning a Script
private var real : Real;
function GetReal(go : GameObject) : Real
{
if (real == null)
real = go.GetComponent(Real);
return real;
}
Example using GameObject
private var targetObject : GameObject;
function OnGUI ()
{
if (GUI.Button(Rect (10,10,100,75), "I am a button") && GetReal(testObject).selected1)
testObject.renderer.material.color = Color.yellow;
}
function GetReal(go : GameObject) : Real
{
if (real == null)
real = go.GetComponent(Real);
return real;
}
I went off on a long rant about coding practices because, well, this question is literally asked at least once a week here. For some reason it keeps getting asked, even though it is answered at least once a week as well. I’m not sure what’s so difficult about performing a google search. It is a lot faster than asking a question on a board and waiting for someone to come around and dilly dally around by critiquing your code and giving you a lot more information than you were probably looking for.
Check it out!